Datasets:

Modalities:
Image
Text
Formats:
parquet
Size:
< 1K
Tags:
code
Libraries:
Datasets
pandas
License:
hackercup / 2021 /round2 /string_concatenation.java
wjomlex's picture
2021 Problems
d3f4f72 verified
raw
history blame
9.74 kB
import java.io.*;
import java.util.*;
/*
Solution by David Harmeyer (SecondThread)
Runtime: O(1e6 + 1e6*log(1e6) + ~4000^2 + ~2^25*(12)), per big testcase, but in practice, that *12 is really more like a * 1
*/
public class StringConcatenation {
static final String filename="input";
static final boolean submit=false, debug=false;
static final int MAX_LEN=1_000_001;
static final int MAX_VAL=1_000_001;
static final Random random=new Random(5);
static void solve(Scanner fs, PrintWriter out) {
int T=fs.nextInt();
for (int tt=0; tt<T; tt++) {
System.err.println("Processing case "+tt);
// we can actually ignore k
int n=fs.nextInt(), k=fs.nextInt();
Str[] strings=new Str[n];
for (int i=0; i<n; i++)
strings[i]=new Str(fs.nextInt(), i+1);
ArrayList<Str>[] ans=solveWithDupesLarge(strings);
if (ans[0].isEmpty()) {
out.println("Case #"+(tt+1)+": Impossible");
}
else {
out.println("Case #"+(tt+1)+": Possible");
for (Str s:ans[0]) out.print(s.id+" ");
out.println();
for (Str s:ans[1]) out.print(s.id+" ");
out.println();
}
}
out.close();
}
//obviously, if we have any two strings of the same length, we can remove duplicates, add them back at the end
static ArrayList<Str>[] solveWithDupesLarge(Str[] strings) {
if (debug) System.out.println("Solving dupes large with "+Arrays.toString(strings));
ArrayList<Str> t1=new ArrayList<>(), t2=new ArrayList<>(), unused=new ArrayList<>();
Str[] ofLen=new Str[MAX_LEN];
for (Str s:strings) {
if (ofLen[s.l]==null) {
ofLen[s.l]=s;
}
else {
t1.add(ofLen[s.l]);
t2.add(s);
ofLen[s.l]=null;
}
}
for (Str s:ofLen) if (s!=null) unused.add(s);
ArrayList<Str>[] solved = solveDedupedLarge(unused);
solved[0].addAll(t1);
solved[1].addAll(t2);
return solved;
}
// now we have no duplicates, so we can remove any triplets i, j, k such that a[i] == a[j] + a[k]
// and any quadruplets i, j, k, l such that a[i] + a[j] == a[k] + a[l]
// This will leave us with at most ~1000 strings.
// We need to be careful to do this faster than n^2 though.
static ArrayList<Str>[] solveDedupedLarge(ArrayList<Str> stringsL) {
if (debug) System.out.println("Solving deduped large with "+stringsL);
int n=stringsL.size();
Str[] strings=new Str[n];
for (int i=0; i<n; i++) strings[i]=stringsL.get(i);
Pair[] withSum=new Pair[MAX_VAL*2];
ArrayList<Str>[] res=new ArrayList[] {new ArrayList<>(), new ArrayList<>(), new ArrayList<>()};
for (int i=0; i<n; i++)
withSum[strings[i].l]=new Pair(strings[i], null);
for (int i=0; i<n; i++) strings[i].positionInList=i;
BIT alive=new BIT(n);
for (int i=0; i<n; i++)
alive.update(i, 1);
// need to be careful not to create nodes with unbalanced degrees. If we create a node
// with a large degree and then it gets deleted, then we have n^2 runtime...
for (int d=1; d<alive.query(0, n-1); d++) {
for (int i=0; i<alive.query(0, n-1) && d<alive.query(0, n-1); i++) {
int j=(d+i)%alive.query(0, n-1);
Str s1=strings[alive.getKth(i)], s2=strings[alive.getKth(j)];
if (s1==s2) continue;
int val=s1.l+s2.l;
if (withSum[val]!=null) {
Pair p=withSum[val];
if(p.a==s1 || p.b==s1 || p.a==s2 || p.b==s2) {
withSum[val]=null;
}
else if (alive.query(p.a.positionInList, p.a.positionInList)==0) {
withSum[val]=null;
}
else if (p.b!=null && alive.query(p.b.positionInList, p.b.positionInList) == 0) {
withSum[val]=null;
}
}
if (withSum[val]==null) {
withSum[val]=new Pair(s1, s2);
continue;
}
else {
Pair p=withSum[val];
res[0].add(p.a);
if (p.b!=null) res[0].add(p.b);
res[1].add(s1);
res[1].add(s2);
Str[] toKill= {p.a, p.b, s1, s2};
for (Str s:toKill) {
if (s!=null) {
alive.update(s.positionInList, -1);
}
}
}
}
}
for (int i=0; i<n; i++)
if (alive.query(i, i)==1)
res[2].add(strings[i]);
ArrayList<Str>[] ans=solveMedium(res[2]);
ans[0].addAll(res[0]);
ans[1].addAll(res[1]);
return ans;
}
// Once we have ~1000 strings left, we can cut the number we have in half by checking random sets of strings
// until we find a collision. The maximum total is ~ 1e6*1000 == 1e9. By the Birthday paradox,
// we should expect to need to check about sqrt(1e9) pairs before finding a pair that works and cutting n in half.
// In reality, it will take fewer steps than that, because these sums won't be uniformly distributed.
// So the expected runtime of one iteration is faster than O(1000 * sqrt(1e9). After one iteration, n is only half as big,
// which means there is no log factor in the runtime of this step, since it is dominated by the case when n is large.
static ArrayList<Str>[] solveMedium(ArrayList<Str> strings) {
if (debug) System.out.println("Solving medium with "+strings);
if (strings.size()<50) return solveSmall(strings);
if (strings.size()>5000) throw null;
HashMap<Long, ArrayList<Str>> groupsWithSum=new HashMap<>();
for (Str s:strings) s.usedIn1=s.usedIn2=false;
int n=strings.size();
while (true) {
ArrayList<Str> group=new ArrayList<>();
long sum=0;
for (Str s:strings) {
if (random.nextBoolean()) {
sum+=s.l;
group.add(s);
}
}
if (groupsWithSum.containsKey(sum)) {
//Then we've found a collision
for (Str s:groupsWithSum.get(sum)) s.usedIn1=true;
for (Str s:group) s.usedIn2=true;
ArrayList<Str>[] res=new ArrayList[] {new ArrayList<>(), new ArrayList<>(), new ArrayList<>()};
for (Str s:strings) {
if (s.usedIn1==s.usedIn2) res[2].add(s);
else if (s.usedIn1) res[0].add(s);
else res[1].add(s);
}
ArrayList<Str>[] ans=solveMedium(res[2]);
ans[0].addAll(res[0]);
ans[1].addAll(res[1]);
return ans;
}
groupsWithSum.put(sum, group);
}
}
// Once we have ~50 strings left, we can repeatedly consider the first 25 of them, remove that pair, and continue
// This will run call solveVerySmall at most 25/2 +1 == 14 times (as each call removes two elements)
// but in practice probably much less than that.
static ArrayList<Str>[] solveSmall(ArrayList<Str> strings) {
if (debug) System.out.println("Solving small with "+strings);
if (strings.size()<=25) {
return solveVerySmall(strings);
}
ArrayList<Str> first25=new ArrayList<>(), rest=new ArrayList<>();
for (Str s:strings) if (first25.size()<25) first25.add(s); else rest.add(s);
ArrayList<Str>[] nextAns=solveVerySmall(first25);
nextAns[2].addAll(rest);
ArrayList<Str>[] ans=solveSmall(nextAns[2]);
ans[0].addAll(nextAns[0]);
ans[1].addAll(nextAns[1]);
return ans;
}
// When we have at most 25 strings left, we can just brute force all subsets in O(2^n)
// k could be down to 23 and this solution would still work.
static ArrayList<Str>[] solveVerySmall(ArrayList<Str> stringsL) {
if (debug) System.out.println("Solving very small with "+stringsL);
Str[] strings=new Str[stringsL.size()];
for (int i=0; i<strings.length; i++) strings[i]=stringsL.get(i);
for (Str s:stringsL) s.usedIn1=s.usedIn2=false;
int n=strings.length;
if (n>25)
throw null;
Str[] lastAdded = new Str[n*MAX_VAL];
int[] sum=new int[1<<n];
for (int i=0; i<n; i++) {
lastAdded[strings[i].l]=strings[i];
sum[1<<i]=strings[i].l;
}
for (int mask=1; mask<1<<n; mask++) {
if (Integer.bitCount(mask)<2) continue;
int lowestBit=Integer.lowestOneBit(mask);
int oldMask=mask-lowestBit;
int added=Integer.numberOfTrailingZeros(lowestBit);
int newSum=sum[oldMask]+strings[added].l;
sum[mask]=newSum;
if (lastAdded[newSum]!=null) {
//then we found a collision
int oldSum=newSum;
while (oldSum!=0) {
Str next=lastAdded[oldSum];
next.usedIn1=true;
oldSum-=next.l;
}
for (int i=0; i<n; i++) {
strings[i].usedIn2=(mask&(1<<i))!=0;
}
ArrayList<Str>[] ans= new ArrayList[] {new ArrayList<>(), new ArrayList<>(), new ArrayList<>()};
for (Str s:strings) {
if (s.usedIn1 == s.usedIn2) {
ans[2].add(s);
}
else if (s.usedIn1) ans[0].add(s);
else ans[1].add(s);
}
return ans;
}
lastAdded[newSum]=strings[added];
}
//checked everything possible and didn't find a match: none exist
return new ArrayList[] {new ArrayList<>(), new ArrayList<>(), (ArrayList) stringsL.clone()};
}
static class Pair {
Str a, b;
public Pair(Str a, Str b) {
this.a=a;
this.b=b;
}
}
static class Str {
int l, id;
boolean usedIn1;
boolean usedIn2;
int positionInList;
public Str(int l, int id) {
this.l=l;
this.id=id;
}
public String toString() {
return l+"";
}
}
static class BIT {
int n, tree[];
public BIT(int N) {
n = N; tree = new int[N + 1];
}
void update(int i, int val) {
for (i++; i <= n; i += i & -i) tree[i] += val;
}
int read(int i) {
int sum = 0;
for (i++; i > 0; i -= i & -i) sum += tree[i];
return sum;
}
// query sum of [l, r] inclusive
int query(int l, int r) { return read(r) - read(l - 1); }
// if the BIT is a freq array, returns the index of the
// kth item (0-indexed), or n if there are <= k items.
int getKth(int k) {
if (k < 0) return -1;
int i = 0;
for (int pw = Integer.highestOneBit(n); pw > 0; pw >>= 1)
if (i + pw <= n && tree[i + pw] <= k) k -= tree[i += pw];
return i;
}
}
public static void main(String[] args) throws FileNotFoundException {
if (!submit) solve(new Scanner(System.in), new PrintWriter(System.out));
else solve(new Scanner(new File(filename+".txt")), new PrintWriter(new File(filename+".out")));
}
}