Split And Differ You are given an array A A of le...

Creado el: 10 de junio de 2026

Respondido usando GPT-5.5 Thinking por Chat01

Pregunta

Split And Differ
You are given an array
A
A of length
N
N.
Find any array
B
B of length at most
3
N
3N, containing positive integers, such that the following conditions hold:

No two adjacent elements of
B
B are equal, and
It is possible to partition
B
B into exactly
N
N non-empty contiguous subarrays such that the sum of the elements in the
i
i-th part is equal to
A
i
A
i

.
Formally, you need to find an integer
K
K and an array
B
1
,
B
2
,

,
B
K
B
1

,B
2

,…,B
K

such that:

1

K

3
N
1≤K≤3N,
1

B
i
1≤B
i

for each
1

i

K
1≤i≤K,
B
i

B
i
+
1
B
i

=B
i+1

for each
1

i
<
K
1≤i<K,
There exist integers
1

L
1

R
1
<
L
2

R
2
<

<
L
N

R
N

K
1=L
1

≤R
1

<L
2

≤R
2

<⋯<L
N

≤R
N

=K such that
L
i

R
i

1
+
1
L
i

=R
i−1

+1 for every
2

i

N
2≤i≤N, and also for every
1

i

N
1≤i≤N,

j

L
i
R
i
B
j

A
i
j=L
i


R
i


B
j

=A
i

If no array satisfying the given conditions exists, output the single integer

1
−1.
If multiple such arrays exist, you may find any of them. In particular, you do not need to minimize or maximize the length of
B
B.

It can be proved that if at least one such array
B
B exists, then there will exist an answer array whose length doesn't exceed
3
N
3N.

Input Format
The first line of input will contain a single integer
T
T, denoting the number of test cases.
Each test case consists of two lines of input.
The first line of each test case contains a single integer
N
N.
The second line contains
N
N space-separated integers
A
1
,
A
2
,

,
A
N
A
1

,A
2

,…,A
N

.
Output Format
For each test case:

If no solution exists, output the single integer

1
−1 on a new line.
If a solution does exist, output two lines.
The first line must contain a single integer
K
K (
1

K

3
N
1≤K≤3N), the length of the array
B
B you found.
The second line must contain
K
K space-separated integers
B
1
,
B
2
,

,
B
K
B
1

,B
2

,…,B
K

, denoting the elements of the array you found.
If there are multiple valid arrays, you may find any of them.

Constraints
1

T

10
5
1≤T≤10
5

1

N

2

10
5
1≤N≤2⋅10
5

1

A
i

2

10
5
1≤A
i

≤2⋅10
5

The sum of
N
N over all test cases won't exceed
2

10
5
2⋅10
5
.
Sample 1:
Input
Output
4
4
1 2 1 3
3
7 7 4
4
7 1 1 8
1
2
4
1 2 1 3
8
4 3 1 2 3 1 3 1
-1
1
2
Explanation:
Test case
1
1: The array
A

[
1
,
2
,
1
,
3
]
A=[1,2,1,3] has no adjacent equal elements already, so simply printing that is a correct answer.

Test case
2
2: For
A

[
7
,
7
,
4
]
A=[7,7,4], consider the array
B

[
4
,
3
,
1
,
2
,
3
,
1
,
3
,
1
]
B=[4,3,1,2,3,1,3,1].

Clearly, no adjacent elements of
B
B are equal.
Further, by splitting
B
B into
[
4
,
3
]
,
[
1
,
2
,
3
,
1
]
,
[
3
,
1
]
[4,3],[1,2,3,1],[3,1] we see that the parts have sums
7
,
7
,
4
7,7,4 as desired.
Thus, this array
B
B satisfies the conditions.
Test case
3
3: It can be shown that no valid array
B
B exists that satisfies the necessary conditions.

give code in cpp without any struct

Pensamiento

Evaluating block lengths needed for constraints

I’m thinking that length 2 blocks might generally suffice to meet the constraints, although length 3 could be necessary in specific cases where a block’s sum implies conflicting boundary values. For example, if a sum is 4, a length 3 block might be needed to avoid conflicts with prior or next block values. However, it doesn't seem like length 3 will be needed often.

Thought for 1m 52s

Respuesta

cpp
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int N; cin >> N; vector<int> A(N); for (int i = 0; i < N; i++) cin >> A[i]; vector<int> B; bool ok = true; int i = 0; while (i < N) { int j = i; while (j < N && A[j] == A[i]) j++; int x = A[i]; int len = j - i; if (len > 1 && x <= 2) { ok = false; break; } if (len == 1) { B.push_back(x); } else { for (int t = 0; t < len; t++) { if (t % 2 == 0) { B.push_back(x); } else { int first = 1; int second = x - 1; if (t == len - 1 && j < N) { int nextVal = A[j]; if (second == nextVal) { first = x - 1; second = 1; } } B.push_back(first); B.push_back(second); } } } i = j; } if (!ok) { cout << -1 << '\n'; } else { cout << B.size() << '\n'; for (int k = 0; k < (int)B.size(); k++) { cout << B[k] << (k + 1 == (int)B.size() ? '\n' : ' '); } } } return 0; }

Idea:
For every maximal equal run of value x:

  • If the run length is 1, just print x.
  • If the run length is more than 1:
    • x = 1 or x = 2 is impossible.
    • Otherwise alternate between:
      • [x]
      • [1, x - 1]

For example, a run like:

text
7 7 7 7

can become:

text
7 | 1 6 | 7 | 1 6

Each part still sums to 7, and adjacent values are never equal.

For the last split of a run, we may swap [1, x - 1] to [x - 1, 1] if needed to avoid matching the first value of the next run.

Pregunta

Basic Tower Defence
You are playing a tower defense game.

Let K

K denote the number of towers you have and P

P denote the power of each tower.
Initially, K=1

K=1 and P=1

P=1.
The game has N

N waves of enemies. The i

i-th wave contains Ai

Ai
​ enemies, each with Hi

Hi
​ health, and all these Ai

Ai
​ enemies must be defeated in at most Si

Si
​ turns to beat the wave.
Each wave proceeds under the following rules:
Every tower locks onto at most one enemy at a time.
Different towers cannot lock onto the same enemy; in particular, if there are fewer alive enemies than towers, some towers do nothing.
Each turn of the wave proceeds as follows:First, each tower that is locked onto an enemy does P

P damage to the enemy it's locked onto.
Then, every enemy whose health is 0

0 or less dies.
Finally, any tower that killed an enemy will immediately lock onto another alive enemy (if it exists).
Once again, note that two towers cannot lock onto the same enemy.
Note that a tower is not allowed to switch targets until it kills the enemy it's locked on to.
After clearing each wave, you can upgrade your setup in one of two ways: either by increasing the number of towers, or by increasing the power of your towers.
That is, you can choose exactly one of the following upgrades:
Increase K

K by 1

1, or
Increase P

P by 1

The chosen upgrade is permanent.
Determine whether there exists a sequence of upgrades that allows you to clear all N

N waves.
Input Format
The first line of input will contain a single integer T

T, denoting the number of test cases.
Each test case consists of multiple lines of input.The first line of each test case contains a single integer N

N — the number of waves.
The next N

N lines describe the waves. The i

i-th of these N

N lines contains three space-separated integers Ai,Hi,

Ai
​,Hi
​, and Si

Si
​, denoting a wave with Ai

Ai
​ enemies each having Hi

Hi
​ health, that needs to be defeated in Si

Si
​ turns.
Output Format
For each test case, output on a new line the answer: Yes if it's possible for all N

N waves to be cleared by choosing upgrades optimally, and No otherwise.

Each letter of the output may be printed in either uppercase or lowercase, i.e. the strings NO, No, nO, and no will all be considered equivalent.
Constraints
1≤T≤105

1≤T≤105
1≤N≤1.5⋅105

1≤N≤1.5⋅105
1≤Ai,Hi,Si≤N

1≤Ai
​,Hi
​,Si
​≤N
The sum of N

N over all test cases does not exceed 1.5⋅105

1.5⋅105
.
Sample 1:
Input

Output

3
3
2 1 2
2 1 1
3 3 3
4
2 1 2
2 1 1
1 1 1
4 2 2
4
1 1 1
4 4 1
2 1 2
3 4 3
Yes
Yes
No
Explanation:
Test case 1: Initially, K=1

K=1 and P=1

P=1.
Wave 1

1 has 2

2 enemies, each with health 1

1, and must be cleared within 2

2 turns.
The single tower kills one enemy in the first turn.
It then locks onto the other enemy and kills it in the second turn, clearing the wave.
Upgrade K

K by 1

  1. Now K=2

K=2 and P=1

P=1.

Wave 2

2 has 2

2 enemies, each with health 1

1, and must be cleared within 1

1 turn.
The two towers lock onto one enemy each, and both enemies are killed in one turn, clearing the wave.
Upgrade K

K by 1

1 again. Now K=3

K=3 and P=1

P=1.

Wave 3

3 has 3

3 enemies, each with health 3

3, and must be cleared within 3

3 turns.
Again, all three towers lock on to one enemy each, and will kill them in three turns. All waves are cleared.
So the answer is Yes.
Test case 3: Initially, K=1

K=1 and P=1

P=1.
Wave 1

1 has 1

1 enemy with health 1

1, and can be cleared in 1

1 turn.
After clearing it, we can perform exactly one upgrade.Either K=2,P=1

K=2,P=1, or
K=1,P=2

K=1,P=2.
Now consider wave 2

2, which has 4

4 enemies, each with health 4

4, and must be cleared within 1

1 turn.
In either case, it is impossible to defeat all 4

4 enemies in just 1

1 turn. Hence, it is impossible to clear all waves.
So the answer is No.

give code in cpp

Python

python
def feas_set(A,H,S,M): res=[] for K in range(1,M): P=M-K import math if ((H+P-1)//P)*((A+K-1)//K)<=S: res.append(K) return res for M in range(2,30): for A in range(1,30): for H in range(1,30): for S in range(1,30): r=feas_set(A,H,S,M) if r: if max(r)-min(r)+1 != len(r): print("noninterval",M,A,H,S,r) raise SystemExit print("all interval small")

Python

python
import math def feas_set(A,H,S,M): return [K for K in range(1,M) if ((H+M-K-1)//(M-K))*((A+K-1)//K)<=S] maxcomp=0; ex=None for M in range(2,80): for A in range(1,80): for H in range(1,80): for S in range(1,80): r=feas_set(A,H,S,M) comps=0 prev=-2 for x in r: if x!=prev+1: comps+=1 prev=x if comps>maxcomp: maxcomp=comps; ex=(M,A,H,S,r) print("maxcomp",maxcomp,ex) print('done', maxcomp, ex[:4])

Python

python
import math def comps_and_gaps(A,H,S,M): r=[] for K in range(1,M): P=M-K if ((H+P-1)//P)*((A+K-1)//K)<=S: r.append(K) gaps=[] for a,b in zip(r,r[1:]): gaps.append(b-a-1) return r,gaps for M in range(2,101): bad=False for A in range(1,101): for H in range(1,101): for S in range(1,101): r,g=comps_and_gaps(A,H,S,M) if g and max(g)>=2: print("gap>=2",M,A,H,S,r, max(g)) raise SystemExit print("no gap>=2 small")

Python

python
import math, random def feasible_intervals(A,H,S,i): M=i+1 intervals=[] k=1 while k<=i: P=M-k x=(A+k-1)//k y=(H+P-1)//P if x>1: r1=(A-1)//(x-1) else: r1=i # max K with same y while P decreasing p_low=(H+y-1)//y # min P for same y r2=M-p_low r=min(i,r1,r2) if x*y<=S: if intervals and intervals[-1][1]+1>=k: intervals[-1]=(intervals[-1][0],r) else: intervals.append((k,r)) k=r+1 return intervals def feasible_set_from_intervals(A,H,S,i): r=[] for l,u in feasible_intervals(A,H,S,i): r += list(range(l,u+1)) return r for i in range(1,50): for A in range(1,50): for H in range(1,50): for S in range(1,50): s1=[K for K in range(1,i+1) if ((H+(i+1-K)-1)//(i+1-K))*((A+K-1)//K)<=S] s2=feasible_set_from_intervals(A,H,S,i) if s1!=s2: print("mismatch",i,A,H,S,s1,s2,feasible_intervals(A,H,S,i)) raise SystemExit print("interval gen ok") def solve_fast(waves): poss={1} N=len(waves) for idx,(A,H,S) in enumerate(waves, start=1): fs=set(feasible_set_from_intervals(A,H,S,idx)) poss=poss & fs if not poss: return False if idx<N: poss = poss | {k+1 for k in poss} return True def solve_brute(waves): poss={1} N=len(waves) for idx,(A,H,S) in enumerate(waves, start=1): M=idx+1 poss={K for K in poss if ((H+(M-K)-1)//(M-K))*((A+K-1)//K)<=S} if not poss: return False if idx<N: poss = poss | {K+1 for K in poss} return True for N in range(1,9): for _ in range(10000): waves=[(random.randint(1,N), random.randint(1,N), random.randint(1,N)) for _ in range(N)] if solve_fast(waves)!=solve_brute(waves): print("dp mismatch",N,waves,solve_fast(waves),solve_brute(waves)) raise SystemExit print("dp ok")

Python

python
import random, subprocess, os, textwrap, tempfile, json, sys, math def brute(waves): poss={1} N=len(waves) for idx,(A,H,S) in enumerate(waves,1): M=idx+1 poss={K for K in poss if ((H+(M-K)-1)//(M-K))*((A+K-1)//K)<=S} if not poss: return False if idx<N: poss |= {K+1 for K in poss} return True tests=[] for N in range(1,15): for _ in range(1000): waves=[(random.randint(1,N),random.randint(1,N),random.randint(1,N)) for _ in range(N)] tests.append(waves) inp=str(len(tests))+"\n" for waves in tests: inp+=str(len(waves))+"\n" for a,h,s in waves: inp+=f"{a} {h} {s}\n" out=subprocess.check_output(["/tmp/main"],input=inp.encode()).decode().strip().splitlines() for waves,ans in zip(tests,out): b=brute(waves) if (ans=="Yes")!=b: print("mismatch",len(waves),waves,ans,b) break else: print("all ok",len(tests))

Pensamiento

import random, subprocess, os, textwrap, tempfile, json, sys, math def brute(waves): poss={1} N=len(waves) for idx,(A,H,S) in enumerate(waves,1): M=idx+1 poss={K for K in poss if ((H+(M-K)-1)//(M-K))*((A+K-1)//K)<=S} if not poss: return False if idx<N: poss |= {K+1 for K in poss} return True

tests=[] for N in range(1,15): for _ in range(1000): waves=[(random.randint(1,N),random.randint(1,N),random.randint(1,N)) for _ in range(N)] tests.append(waves) inp=str(len(tests))+"\n" for waves in tests: inp+=str(len(waves))+"\n" for a,h,s in waves: inp+=f"{a} {h} {s}\n" out=subprocess.check_output(["/tmp/main"],input=inp.encode()).decode().strip().splitlines() for waves,ans in zip(tests,out): b=brute(waves) if (ans=="Yes")!=b: print("mismatch",len(waves),waves,ans,b) break else: print("all ok",len(tests))

Thought for 5m 51s

Respuesta

cpp
#include <bits/stdc++.h> using namespace std; using ull = unsigned long long; void setRange(vector<ull>& bits, int l, int r) { if (l > r) return; int wl = l >> 6, wr = r >> 6; int bl = l & 63, br = r & 63; ull leftMask = (~0ULL << bl); ull rightMask = (br == 63 ? ~0ULL : ((1ULL << (br + 1)) - 1)); if (wl == wr) { bits[wl] |= (leftMask & rightMask); } else { bits[wl] |= leftMask; for (int w = wl + 1; w < wr; w++) bits[w] = ~0ULL; bits[wr] |= rightMask; } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; while (T--) { int N; cin >> N; vector<int> A(N + 1), H(N + 1), S(N + 1); for (int i = 1; i <= N; i++) { cin >> A[i] >> H[i] >> S[i]; } int W = (N + 70) / 64; vector<ull> possible(W, 0), mask(W, 0); possible[0] = 2ULL; // K = 1 is possible initially bool ok = true; for (int i = 1; i <= N; i++) { int activeWords = (i >> 6) + 1; fill(mask.begin(), mask.begin() + activeWords, 0ULL); int total = i + 1; // K + P before wave i int k = 1; while (k <= i) { int p = total - k; long long enemiesPerTower = (A[i] + k - 1LL) / k; long long turnsPerEnemy = (H[i] + p - 1LL) / p; int r1; if (enemiesPerTower == 1) { r1 = i; } else { r1 = (int)min<long long>( i, (A[i] - 1LL) / (enemiesPerTower - 1) ); } long long minPowerSame = (H[i] + turnsPerEnemy - 1LL) / turnsPerEnemy; int r2 = total - (int)minPowerSame; int r = min(r1, r2); if (enemiesPerTower * turnsPerEnemy <= S[i]) { setRange(mask, k, r); } k = r + 1; } bool any = false; for (int w = 0; w < activeWords; w++) { possible[w] &= mask[w]; if (possible[w]) any = true; } if (!any) { ok = false; break; } if (i < N) { int nextWords = ((i + 1) >> 6) + 1; ull carry = 0; for (int w = 0; w < nextWords; w++) { ull old = possible[w]; ull shifted = (old << 1) | carry; carry = old >> 63; possible[w] |= shifted; } } } cout << (ok ? "Yes" : "No") << '\n'; } return 0; }

For a wave, if current values are K and P:

text
turns needed by one tower to kill one enemy = ceil(H / P) enemies handled by one tower group count = ceil(A / K)

So the wave is clearable iff:

text
ceil(H / P) * ceil(A / K) <= S

Before wave i, we always have:

text
K + P = i + 1

The code keeps a bitset of all possible K values before each wave. After clearing a wave, upgrading means either:

text
K stays same

or

text
K increases by 1

So the bitset becomes:

text
possible OR (possible << 1)

Compartir este Q&A