git reimport
This commit is contained in:
67
archive/2016.08/2016.08.01 - unsorted/Sazanka0G.java
Normal file
67
archive/2016.08/2016.08.01 - unsorted/Sazanka0G.java
Normal file
@@ -0,0 +1,67 @@
|
||||
package chelper;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import io.InputReader;
|
||||
import io.OutputWriter;
|
||||
|
||||
public class Sazanka0G {
|
||||
int[] powers = new int[10];
|
||||
|
||||
public void solve(int testNumber, InputReader in, OutputWriter out) {
|
||||
int k = 6;
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
powers[i] = (int) Math.pow(i, k);
|
||||
}
|
||||
|
||||
int[] dp = new int[10000000];
|
||||
Arrays.fill(dp, -1);
|
||||
|
||||
long sum = 0;
|
||||
for (int i = 1; i <= 1000000; i++) {
|
||||
sum += f(i, dp);
|
||||
}
|
||||
out.println(sum);
|
||||
}
|
||||
|
||||
int nextHappy(int n) {
|
||||
int x = n;
|
||||
int ans = 0;
|
||||
while (x > 0) {
|
||||
int t = x % 10;
|
||||
x /= 10;
|
||||
ans += powers[t];
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
|
||||
int f(int x, int[] dp) {
|
||||
if (dp[x] == -1) {
|
||||
int t = nextHappy(x);
|
||||
dp[x] = -2;
|
||||
dp[x] = Math.min(x, f(t, dp));
|
||||
}
|
||||
if (dp[x] == -2) { // found loop
|
||||
Set<Integer> loop = new HashSet<>();
|
||||
int t = x;
|
||||
while (true) {
|
||||
loop.add(t);
|
||||
t = nextHappy(t);
|
||||
if (t == x) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
int min = Integer.MAX_VALUE;
|
||||
for (int i : loop) {
|
||||
min = Math.min(min, i);
|
||||
}
|
||||
for (int i : loop) {
|
||||
dp[i] = min;
|
||||
}
|
||||
}
|
||||
return dp[x];
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user