exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
sequencelengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | b108aeff97603341f1a87ae8c07373a8 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.*;
import java.lang.*;
import java.util.*;
public class ComdeFormces {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
FastReader sc=new FastReader();
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
int t=sc.nextInt();
long val=1000000;
ArrayList<Long> ar=new ArrayList<>();
long p=1;
long i=1;
while(p<=val*val) {
p*=i;
ar.add(p);
i++;
}
ar.remove(ar.size()-1);
while(t--!=0) {
long n=sc.nextLong();
log.write(eval(ar,n,ar.size()-1)+"\n");
log.flush();
}
}
static int eval(ArrayList<Long> ar, long n, int j) {
if(j<0)return bits(n);
if(n==0)return 0;
if(n-ar.get(j)>=0) {
return Math.min(eval(ar,n,j-1), 1+eval(ar,n-ar.get(j),j-1));
}
return eval(ar,n,j-1);
}
static int bits(long n) {
int ans=0;
while(n!=0) {
if((n&1)==1)ans++;
n>>=1;
}
return ans;
}
static long flor(ArrayList<Long> ar,long el) {
int s=0;
int e=ar.size()-1;
while(s<=e) {
int m=s+(e-s)/2;
if(ar.get(m)==el)return ar.get(m);
else if(ar.get(m)<el)s=m+1;
else e=m-1;
}
return e>=0?e:-1;
}
//static int fd(pair a[], long wd,int e) {
// int s=0;
// while(s<=e) {
// int m=s+(e-s)/2;
// }
//
// return -2;
//}
public static int kadane(int a[]) {
int sum=0,mx=Integer.MIN_VALUE;
for(int i=0;i<a.length;i++) {
sum+=a[i];
mx=Math.max(mx, sum);
if(sum<0) sum=0;
}
return mx;
}
public static int rec( int l,int[] dp) {
if(l<=2)return 1;
if(dp[l]!=0)return dp[l];
int f=0,s=0;
if(dp[l-1]!=0)f=dp[l-1];
else f=rec(l-1,dp);
if(dp[l-2]!=0)s=dp[l-2];
else s=rec(l-2,dp);
return dp[l]=add(f,s);
}
public static int m=1000000007;
public static int mul(int a, int b) {
return ((a%m)*(b%m))%m;
}
public static int add(int a, int b) {
return ((a%m)+(b%m))%m;
}
public static String rever(String s) {
char a[]=s.toCharArray();
for(int i=0;i<a.length/2;i++) {
char temp=a[i];
a[i]=a[a.length-1-i];
a[a.length-1-i]=temp;
}
return String.valueOf(a);
}
//static ArrayList<Integer> pr(int n){
// boolean vis[]=new boolean[n+1];
// vis[0]=false;
// vis[1]=false;
// for(int i=2;i<=n;i++) {
// if(vis[i]) {
// for(int j=2*i;j<=n;j+=i) {
// vis[j]=false;
// }
// }
// }
//}
static int subset(int a[],int j,int dp[][], int sum) {
if(j==0) {
if(sum==0 || sum-a[j]==0)return 1;
else return 0;
}
if(sum==0)return 1;
if(dp[j][sum]>0)return dp[j][sum];
// p("for j="+j+"sum="+sum,"s");
if(sum-a[j]>=0) {
int p=subset(a,j-1,dp,sum-a[j]);
int q=subset(a,j-1,dp,sum);
return dp[j][sum]=p+q;
}
else{
return dp[j][sum]=subset(a,j-1,dp,sum);
}
}
static long slv(int a[],int b[],long dp[][],int end,int k,int i) {
if(i<1 ) {
if(k==0) {
return (end-a[0])*b[0];
}
else return Integer.MAX_VALUE;
}
if(k<0)return Integer.MAX_VALUE;
if(k==0) {
return (end-a[0])*b[0];
}
if(dp[i][k]!=0)return dp[i][k];
long ans1=slv(a,b,dp,a[i],k-1,i-1);
long ans2=slv(a,b,dp,end,k,i-1);
long val=(end-a[i])*b[i];
return dp[i][k]=Math.min(val+ans1,ans2);
}
static int bss(int[] a,int s, long k) {
int e=a.length-1;
// int max=-1;
while(s<=e) {
int m=s+(e-s)/2;
if(a[m]==k) {
return m;
}
else if(a[m]<k)s=m+1;
else e=m-1;
}
return -1;
}
static int solv(int[] a,int len) {
if(len%2==0) {
int ans=0;
for(int i=0;i<a.length;i++){
if(a[i]>0){
if(a[i]%2==0) {
ans+=a[i];
}
else if(a[i]%2!=0) {
ans+=(a[i]/2)*2;
}
}
}
int cnt=ans/len;
return cnt;
}
else {
int ans=0,one=0;
for(int i=0;i<a.length;i++){
if(a[i]>0){
if(a[i]%2==0) {
ans+=a[i];
}
else {
ans+=(a[i]/2)*2;
one++;
}
}
}
int n=len-1;
int cnt=ans/n;
int mod=cnt%n+one;
if(cnt>=mod)return cnt;
return mod;
}
}
//debug
static pair bss(ArrayList<pair> a,int el,int ind) {
int s=0;
int e=a.size()-1;
pair ans=new pair(-1,-1);
while(s<=e) {
int m=s+(e-s)/2;
if(a.get(m).a==el) {
ans=a.get(m);
e=m-1;
}
if(a.get(m).a>el)e=m-1;
else s=m+1;
}
return ans;
}
public static <E> void p(E[][] a,String s) {
System.out.println(s);
for(int i=0;i<a.length;i++) {
for(int j=0;j<a[0].length;j++) {
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
public static void p(int[] a,String s) {
System.out.print(s+"=");
for(int i=0;i<a.length;i++)System.out.print(a[i]+" ");
System.out.println();
}
public static <E> void p(E a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(ArrayList<E> a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(LinkedList<E> a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(HashSet<E> a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(Stack<E> a,String s){
System.out.println(s+"="+a);
}
public static <E> void p(Queue<E> a,String s){
System.out.println(s+"="+a);
}
//utils
static ArrayList<Integer> divisors(int n){
ArrayList<Integer> ar=new ArrayList<>();
for (int i=2; i<=Math.sqrt(n); i++){
if (n%i == 0){
if (n/i == i) {
ar.add(i);
}
else {
ar.add(i);
ar.add(n/i);
}
}
}
return ar;
}
static int primeDivisor(int n){
ArrayList<Integer> ar=new ArrayList<>();
int cnt=0;
boolean pr=false;
while(n%2==0) {
pr=true;
n/=2;
}
if(pr)ar.add(2);
for(int i=3;i*i<=n;i+=2) {
pr=false;
while(n%i==0) {
n/=i;
pr=true;
}
if(pr)ar.add(i);
}
if(n>2) ar.add(n);
return ar.size();
}
static String rev(String s) {
char temp[]=s.toCharArray();
for(int i=0;i<temp.length/2;i++) {
char tp=temp[i];
temp[i]=temp[temp.length-1-i];
temp[temp.length-1-i]=tp;
}
return String.valueOf(temp);
}
static int bs(ArrayList<pair> arr,int el) {
int start=0;
int end=arr.size()-1;
while(start<=end) {
int mid=start+(end-start)/2;
if(arr.get(mid).a==el)return mid;
else if(arr.get(mid).a<el)start=mid+1;
else end=mid-1;
}
if(start>arr.size()-1)return -2;
return -1;
}
static long find(int s,long a[]) {
if(s>=a.length)return -1;
long num=a[s];
for(int i=s;i<a.length;i+=2) {
num=gcd(num,a[i]);
if(num==1 || num==0)return -1;
}
return num;
}
static long gcd(long a,long b) {
if(b==0)return a;
else return gcd(b,a%b);
}
static int gcd(int a,int b) {
if(b==0)return a;
else return gcd(b,a%b);
}
static long factmod(long n,long mod,long img) {
if(n==0)return 1;
long ans=1;
long temp=1;
while(n--!=0) {
if(temp!=img) {
ans=((ans%mod)*((temp)%mod))%mod;
}
temp++;
}
return ans%mod;
}
static int bs(long a[] ,long num) {
int start=0;
int end=a.length-1;
while(start<=end) {
int mid=start+(end-start)/2;
if(a[mid]==num) {
return mid;
}
else if(a[mid]<num)start=mid+1;
else end=mid-1;
}
return start;
}
static int ncr(int n, int r){
if(r>n-r)r=n-r;
int ans=1;
for(int i=0;i<r;i++){
ans*=(n-i);
ans/=(i+1);
}
return ans;
}
public static class trip{
long a,b;
int c;
public trip(long a,long b,int c) {
this.a=a;
this.b=b;
this.c=c;
}
public int compareTo(trip q) {
return (int)(this.a-q.a);
}
}
static void mergesort(long[] a,int start,int end) {
if(start>=end)return ;
int mid=start+(end-start)/2;
mergesort(a,start,mid);
mergesort(a,mid+1,end);
merge(a,start,mid,end);
}
static void merge(long[] a, int start,int mid,int end) {
int ptr1=start;
int ptr2=mid+1;
long b[]=new long[end-start+1];
int i=0;
while(ptr1<=mid && ptr2<=end) {
if(a[ptr1]<=a[ptr2]) {
b[i]=a[ptr1];
ptr1++;
i++;
}
else {
b[i]=a[ptr2];
ptr2++;
i++;
}
}
while(ptr1<=mid) {
b[i]=a[ptr1];
ptr1++;
i++;
}
while(ptr2<=end) {
b[i]=a[ptr2];
ptr2++;
i++;
}
for(int j=start;j<=end;j++) {
a[j]=b[j-start];
}
}
public static class FastReader {
BufferedReader b;
StringTokenizer s;
public FastReader() {
b=new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(s==null ||!s.hasMoreElements()) {
try {
s=new StringTokenizer(b.readLine());
}
catch(IOException e) {
e.printStackTrace();
}
}
return s.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str="";
try {
str=b.readLine();
}
catch(IOException e) {
e.printStackTrace();
}
return str;
}
boolean hasNext() {
if (s != null && s.hasMoreTokens()) {
return true;
}
String tmp;
try {
b.mark(1000);
tmp = b.readLine();
if (tmp == null) {
return false;
}
b.reset();
} catch (IOException e) {
return false;
}
return true;
}
}
public static class pair{
long a;
long b;
public pair(long a,long b) {
this.a=a;
this.b=b;
}
// public int compareTo(pair b) {
// return this.a-b.a;
//
// }
// public int compareToo(pair b) {
// return this.b-b.b;
// }
@Override
public String toString() {
return "{"+this.a+" "+this.b+"}";
}
}
static long pow(long a, long pw) {
long temp;
if(pw==0)return 1;
temp=pow(a,pw/2);
if(pw%2==0)return temp*temp;
return a*temp*temp;
}
static int pow(int a, int pw) {
int temp;
if(pw==0)return 1;
temp=pow(a,pw/2);
if(pw%2==0)return temp*temp;
return a*temp*temp;
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 7ec09b7e31fcdbeb1e5978228e05c83b | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.*;
import javax.print.DocFlavor.INPUT_STREAM;
import java.io.*;
import java.math.*;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
public class Main {
private static class MyScanner {
private static final int BUF_SIZE = 2048;
BufferedReader br;
private MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private boolean isSpace(char c) {
return c == '\n' || c == '\r' || c == ' ';
}
String next() {
try {
StringBuilder sb = new StringBuilder();
int r;
while ((r = br.read()) != -1 && isSpace((char)r));
if (r == -1) {
return null;
}
sb.append((char) r);
while ((r = br.read()) != -1 && !isSpace((char)r)) {
sb.append((char)r);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
static class Reader{
BufferedReader br;
StringTokenizer st;
public Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static long mod = (long)(1e9 + 7);
static void sort(long[] arr ) {
ArrayList<Long> al = new ArrayList<>();
for(long e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(int[] arr ) {
ArrayList<Integer> al = new ArrayList<>();
for(int e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(char[] arr) {
ArrayList<Character> al = new ArrayList<Character>();
for(char cc:arr) al.add(cc);
Collections.sort(al);
for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i);
}
static long mod_mul( long... a) {
long ans = a[0]%mod;
for(int i = 1 ; i<a.length ; i++) {
ans = (ans * (a[i]%mod))%mod;
}
return ans;
}
static long mod_sum( long... a) {
long ans = 0;
for(long e:a) {
ans = (ans + e)%mod;
}
return ans;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void print(long[] arr) {
System.out.println("---print---");
for(long e:arr) System.out.print(e+" ");
System.out.println("-----------");
}
static void print(int[] arr) {
System.out.println("---print---");
for(long e:arr) System.out.print(e+" ");
System.out.println("-----------");
}
static boolean[] prime(int num) {
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long modInverse(long a, long m)
{
long g = gcd(a, m);
return power(a, m - 2);
}
static long lcm(long a , long b) {
return (a*b)/gcd(a, b);
}
static int lcm(int a , int b) {
return (int)((a*b)/gcd(a, b));
}
static long power(long x, long y){
if(y<0) return 0;
long m = mod;
if (y == 0) return 1; long p = power(x, y / 2) % m; p = (int)((p * (long)p) % m);
if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }
static class Combinations{
private long[] z; // factorial
private long[] z1; // inverse factorial
private long[] z2; // incerse number
private long mod;
public Combinations(long N , long mod) {
this.mod = mod;
z = new long[(int)N+1];
z1 = new long[(int)N+1];
z[0] = 1;
for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;
z2 = new long[(int)N+1];
z2[0] = z2[1] = 1;
for (int i = 2; i <= N; i++)
z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;
z1[0] = z1[1] = 1;
for (int i = 2; i <= N; i++)
z1[i] = (z2[i] * z1[i - 1]) % mod;
}
long fac(long n) {
return z[(int)n];
}
long invrsNum(long n) {
return z2[(int)n];
}
long invrsFac(long n) {
return z1[(int)n];
}
long ncr(long N, long R)
{ if(R<0 || R>N ) return 0;
long ans = ((z[(int)N] * z1[(int)R])
% mod * z1[(int)(N - R)])
% mod;
return ans;
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static int max(int... a ) {
int max = a[0];
for(int e:a) max = Math.max(max, e);
return max;
}
static long max(long... a ) {
long max = a[0];
for(long e:a) max = Math.max(max, e);
return max;
}
static int min(int... a ) {
int min = a[0];
for(int e:a) min = Math.min(e, min);
return min;
}
static long min(long... a ) {
long min = a[0];
for(long e:a) min = Math.min(e, min);
return min;
}
static int[] KMP(String str) {
int n = str.length();
int[] kmp = new int[n];
for(int i = 1 ; i<n ; i++) {
int j = kmp[i-1];
while(j>0 && str.charAt(i) != str.charAt(j)) {
j = kmp[j-1];
}
if(str.charAt(i) == str.charAt(j)) j++;
kmp[i] = j;
}
return kmp;
}
/************************************************ Query **************************************************************************************/
/***************************************** Sparse Table ********************************************************/
static class SparseTable{
private long[][] st;
SparseTable(long[] arr){
int n = arr.length;
st = new long[n][25];
log = new int[n+2];
build_log(n+1);
build(arr);
}
private void build(long[] arr) {
int n = arr.length;
for(int i = n-1 ; i>=0 ; i--) {
for(int j = 0 ; j<25 ; j++) {
int r = i + (1<<j)-1;
if(r>=n) break;
if(j == 0 ) st[i][j] = arr[i];
else st[i][j] = Math.min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );
}
}
}
public long gcd(long a ,long b) {
if(a == 0) return b;
return gcd(b%a , a);
}
public long query(int l ,int r) {
int w = r-l+1;
int power = log[w];
return Math.min(st[l][power],st[r - (1<<power) + 1][power]);
}
private int[] log;
void build_log(int n) {
log[1] = 0;
for(int i = 2 ; i<=n ; i++) {
log[i] = 1 + log[i/2];
}
}
}
/******************************************************** Segement Tree *****************************************************/
static class SegmentTree{
long[] tree;
long[] arr;
int n;
SegmentTree(long[] arr){
this.n = arr.length;
tree = new long[4*n+1];
this.arr = arr;
buildTree(0, n-1, 1);
}
void buildTree(int s ,int e ,int index ) {
if(s == e) {
tree[index] = arr[s];
return;
}
int mid = (s+e)/2;
buildTree( s, mid, 2*index);
buildTree( mid+1, e, 2*index+1);
tree[index] = gcd(tree[2*index] , tree[2*index+1]);
}
long query(int si ,int ei) {
return query(0 ,n-1 , si ,ei , 1 );
}
private long query( int ss ,int se ,int qs , int qe,int index) {
if(ss>=qs && se<=qe) return tree[index];
if(qe<ss || se<qs) return (long)(0);
int mid = (ss + se)/2;
long left = query( ss , mid , qs ,qe , 2*index);
long right= query(mid + 1 , se , qs ,qe , 2*index+1);
return gcd(left, right);
}
public void update(int index , int val) {
arr[index] = val;
// for(long e:arr) System.out.print(e+" ");
update(index , 0 , n-1 , 1);
}
private void update(int id ,int si , int ei , int index) {
if(id < si || id>ei) return;
if(si == ei ) {
tree[index] = arr[id];
return;
}
if(si > ei) return;
int mid = (ei + si)/2;
update( id, si, mid , 2*index);
update( id , mid+1, ei , 2*index+1);
tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);
}
}
/* ***************************************************************************************************************************************************/
// static MyScanner sc = new MyScanner(); // only in case of less memory
static Reader sc = new Reader();
static int TC;
static StringBuilder sb = new StringBuilder();
static PrintWriter out=new PrintWriter(System.out);
public static void main(String args[]) throws IOException {
int tc = 1;
tc = sc.nextInt();
TC = 0;
for(int i = 1 ; i<=tc ; i++) {
TC++;
// sb.append("Case #" + i + ": " ); // During KickStart && HackerCup
TEST_CASE();
}
System.out.print(sb);
}
static void TEST_CASE() throws IOException {
long n = sc.nextLong();
Set<Long> set = new HashSet<>();
ArrayList<Long> al = new ArrayList<>();
long f = 1;
long num = 2;
while(f<=1e13) {
set.add(f);
f *= num;
num++;
}
set.remove(2l);
set.remove(1l);
al.addAll(set);
Collections.sort(al);
// System.out.println(al);
ans = count(n);
// System.out.println(ans);
fnc(n, 0, new HashSet<>(), al);
if(ans>=80) {
sb.append("-1\n");
return;
}
sb.append(ans+"\n");
}
static long ans;
static long count(long num ) {
long c = 0;
// if(num %2 == 1) return 100;
for(int i = 0 ; i<60 ; i++) {
long piv = 1l<<i;
if((piv&num) != 0) {
// System.out.println(piv);
c++;
}
}
// System.out.println("c- "+c);
return c;
}
static void fnc(long num ,int i , Set<Long> set , ArrayList<Long> al) {
if(i == al.size()) return;
ans = min(ans , count(num) + set.size());
// System.out.println(num +" "+ans);
if(num - al.get(i)>= 0) {
set.add(al.get(i));
fnc(num-al.get(i), i+1, set, al);
set.remove(al.get(i));
}
fnc(num, i+1, set, al);
}
}
/*******************************************************************************************************************************************************/
/**
*/
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | d12bc66d3187307fdaee10f01c71998f | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
public class C_Factorials_and_Powers_of_Two {
static long mod = Long.MAX_VALUE;
public static void main(String[] args) {
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
FastReader f = new FastReader();
int t = f.nextInt();
while(t-- > 0){
solve(f, out);
}
out.close();
}
public static void solve(FastReader f, PrintWriter out) {
long n = f.nextLong();
ArrayList<Long> arrli = new ArrayList<>();
long fact = 2;
for(int i = 3; i <= 14; i++) {
fact *= i;
arrli.add(fact);
}
out.println(internal(arrli, n, 0l, 0));
}
public static int internal(ArrayList<Long> arrli, long n, long x, int ind) {
if(ind == arrli.size()) {
return setBitCount(n-x);
}
int take = (x+arrli.get(ind) <= n) ? internal(arrli, n, x+arrli.get(ind), ind+1) + 1 : Integer.MAX_VALUE;
int notTake = internal(arrli, n, x, ind+1);
return min(take, notTake);
}
public static int setBitCount(long x) {
int count = 0;
while(x > 0) {
count++;
x = x&(x-1);
}
return count;
}
// Sort an array
public static void sort(int arr[]) {
ArrayList<Integer> al = new ArrayList<>();
for(int i: arr) {
al.add(i);
}
Collections.sort(al);
for(int i = 0; i < arr.length; i++) {
arr[i] = al.get(i);
}
}
// Find all divisors of n
public static void allDivisors(int n) {
for(int i = 1; i*i <= n; i++) {
if(n%i == 0) {
System.out.println(i + " ");
if(i != n/i) {
System.out.println(n/i + " ");
}
}
}
}
// Check if n is prime or not
public static boolean isPrime(int n) {
if(n < 1) return false;
if(n == 2 || n == 3) return true;
if(n % 2 == 0 || n % 3 == 0) return false;
for(int i = 5; i*i <= n; i += 6) {
if(n % i == 0 || n % (i+2) == 0) {
return false;
}
}
return true;
}
// Find gcd of a and b
public static long gcd(long a, long b) {
long dividend = a > b ? a : b;
long divisor = a < b ? a : b;
while(divisor > 0) {
long reminder = dividend % divisor;
dividend = divisor;
divisor = reminder;
}
return dividend;
}
// Find lcm of a and b
public static long lcm(long a, long b) {
long lcm = gcd(a, b);
long hcf = (a * b) / lcm;
return hcf;
}
// Find factorial in O(n) time
public static long fact(int n) {
long res = 1;
for(int i = 2; i <= n; i++) {
res = res * i;
}
return res;
}
// Find power in O(logb) time
public static long power(long a, long b) {
long res = 1;
while(b > 0) {
if((b&1) == 1) {
res = (res * a)%mod;
}
a = (a * a)%mod;
b >>= 1;
}
return res;
}
// Find nCr
public static long nCr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / (fact(r) * fact(n-r));
return ans;
}
// Find nPr
public static long nPr(int n, int r) {
if(r < 0 || r > n) {
return 0;
}
long ans = fact(n) / fact(r);
return ans;
}
// sort all characters of a string
public static String sortString(String inputString) {
char tempArray[] = inputString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
// User defined class for fast I/O
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
boolean hasNext() {
if (st != null && st.hasMoreTokens()) {
return true;
}
String tmp;
try {
br.mark(1000);
tmp = br.readLine();
if (tmp == null) {
return false;
}
br.reset();
} catch (IOException e) {
return false;
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextArray(int n) {
int[] a = new int[n];
for(int i=0; i<n; i++) {
a[i] = nextInt();
}
return a;
}
}
}
/**
Dec Char Dec Char Dec Char Dec Char
--------- --------- --------- ----------
0 NUL (null) 32 SPACE 64 @ 96 `
1 SOH (start of heading) 33 ! 65 A 97 a
2 STX (start of text) 34 " 66 B 98 b
3 ETX (end of text) 35 # 67 C 99 c
4 EOT (end of transmission) 36 $ 68 D 100 d
5 ENQ (enquiry) 37 % 69 E 101 e
6 ACK (acknowledge) 38 & 70 F 102 f
7 BEL (bell) 39 ' 71 G 103 g
8 BS (backspace) 40 ( 72 H 104 h
9 TAB (horizontal tab) 41 ) 73 I 105 i
10 LF (NL line feed, new line) 42 * 74 J 106 j
11 VT (vertical tab) 43 + 75 K 107 k
12 FF (NP form feed, new page) 44 , 76 L 108 l
13 CR (carriage return) 45 - 77 M 109 m
14 SO (shift out) 46 . 78 N 110 n
15 SI (shift in) 47 / 79 O 111 o
16 DLE (data link escape) 48 0 80 P 112 p
17 DC1 (device control 1) 49 1 81 Q 113 q
18 DC2 (device control 2) 50 2 82 R 114 r
19 DC3 (device control 3) 51 3 83 S 115 s
20 DC4 (device control 4) 52 4 84 T 116 t
21 NAK (negative acknowledge) 53 5 85 U 117 u
22 SYN (synchronous idle) 54 6 86 V 118 v
23 ETB (end of trans. block) 55 7 87 W 119 w
24 CAN (cancel) 56 8 88 X 120 x
25 EM (end of medium) 57 9 89 Y 121 y
26 SUB (substitute) 58 : 90 Z 122 z
27 ESC (escape) 59 ; 91 [ 123 {
28 FS (file separator) 60 < 92 \ 124 |
29 GS (group separator) 61 = 93 ] 125 }
30 RS (record separator) 62 > 94 ^ 126 ~
31 US (unit separator) 63 ? 95 _ 127 DEL
*/
// (a/b)%mod == (a * moduloInverse(b)) % mod;
// moduloInverse(b) = power(b, mod-2);
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 7147bde1b9121b8e439c090c60647eae | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | // package FirstPackage;
import java.util.*;
import java.lang.Math;
import java.io.* ;
public class Account {
public static class Pair<Object1 ,Object2> {
Object1 key ;
Object2 val ;
Pair(Object1 key ,Object2 val) {
this.key = key ;
this.val = val ;
}
Pair() {}
}
static int mod = (int)(1e9+7) ;
public static void main(String[] args) {
// Scanner sc = new Scanner(System.in) ;
FastReader sc = new FastReader() ;
// StringBuilder res = new StringBuilder() ;
// int t = 1 ;
int t = sc.nextInt() ;
while(t-- > 0) {
long n = sc.nextLong() ;
List<Long> fact = getFact(n) ;
System.out.println(solve(n ,0 ,fact));
}
}
public static long solve(long tar ,int idx ,List<Long> fact) {
if(idx == fact.size()) {
return getOnes(tar) ;
}
if(fact.get(idx) <= tar) {
return Math.min(solve(tar-fact.get(idx) ,idx+1 ,fact)+1, solve(tar ,idx+1 ,fact)) ;
}else {
return solve(tar ,idx+1 ,fact) ;
}
}
public static int getOnes(long x) {
int ones = 0 ;
while(x > 0) {
ones++ ;
x = x & (x-1) ;
}
return ones ;
}
public static List<Long> getFact(long n) {
List<Long> fact = new ArrayList<>() ;
long x = 1 ,k = 1 ;
while(x <= n) {
x *= k++ ;
fact.add(x) ;
}
return fact ;
}
/*
* 1 1 1 2 2 3 4 4 4 5
* 100
*
* [1,7,7,7,7,7,7,7,9,9,9,9,9,9,9,9,9]
*/
public static long lcmOfArray(int[] arr, int idx) {
// lcm(a,b) = (a*b/gcd(a,b))
if (idx == arr.length - 1){
return arr[idx];
}
long a = arr[idx];
long b = lcmOfArray(arr, idx+1);
return (a*b/gcd(a,b));
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static long fact(int n) {
if(n == 0 || n == 1) {
return 1 ;
}
int mod = (int)(1e9+7) ;
long fac = 1 ;
while(n > 1) {
fac = mul(fac ,n--) ;
fac = (fac * n--)%mod ;
}
return fac ;
}
// _xor from 1 to n
public static int xor(int n) {
if (n % 4 == 0)
return n;
if (n % 4 == 1)
return 1;
if (n % 4 == 2)
return n + 1;
return 0;
}
// mod operations :
public static long add(long a, long b) {
return (a+b)%mod;
}
public static long sub(long a, long b) {
return ((a-b)%mod+mod)%mod;
}
public static long mul(long a, long b) {
return (a*b)%mod;
}
/*
* Can instantiate SGTNode object like
* (i) root = new SGTNode() ;
* root.buildTree(nums) ;
* or
* (ii) root = new SGTNode(nums) ;
*
* where nums is an array
*/
public static class SGTNode {
int val ,low ,high ;
SGTNode left ,right ;
public SGTNode() {}
public SGTNode(int[] arr){
this.buildTree(arr) ;
}
public SGTNode(int val ,int low ,int high) {
this.val = val ;
this.low = low ;
this.high = high ;
}
public SGTNode(int val ,int low ,int high ,SGTNode left ,SGTNode right) {
this.val = val ;
this.low = low ;
this.high = high ;
this.left = left ;
this.right = right ;
}
public void buildTree(int[] arr) { // O(n)
SGTNode root = buildTreeHelper(this ,arr ,0 ,arr.length-1) ;
// return root ;
}
public SGTNode buildTreeHelper(SGTNode root ,int[] arr ,int low ,int high) {
if(high == low) {
// return new SGTNode(arr[low] ,low ,high) ;
root.val = arr[low] ;
root.low = low ;
root.high = high ;
return root ;
}
int mid = low + (high - low) / 2 ;
root.left = buildTreeHelper(new SGTNode() ,arr ,low ,mid) ;
root.right = buildTreeHelper(new SGTNode() ,arr ,mid+1 ,high) ;
root.val = root.left.val + root.right.val ; // Computable
root.low = low ;
root.high = high ;
return root ;
// return new SGTNode(left.val+right.val ,low ,high ,left ,right) ;
}
public void update(int ind ,int val) { // O(logn)
updateHelper(this ,ind ,val) ;
}
public void updateHelper(SGTNode root ,int ind ,int val) {
if(root.low == root.high) {
root.val = val ;
return ;
}
int mid = root.low + (root.high - root.low) / 2 ;
if(ind <= mid) {
updateHelper(root.left ,ind ,val) ;
}else {
updateHelper(root.right ,ind ,val) ;
}
root.val = root.left.val + root.right.val ; // Computable
}
public int sumRange(int low ,int high) { // O(logn)
return sumRangeHelper(this ,low ,high) ;
}
public int sumRangeHelper(SGTNode root ,int low ,int high) {
if(root.low == low && high == root.high) { // complete overlap
return root.val ;
}
// partial overlap
int mid = root.low + (root.high - root.low) / 2 ;
if(high <= mid) {
return sumRangeHelper(root.left ,low ,high) ;
}if(low >= mid+1) {
return sumRangeHelper(root.right ,low ,high) ;
}
int left = sumRangeHelper(root.left ,low ,mid) ;
int right = sumRangeHelper(root.right ,mid+1 ,high) ;
return left + right ;
}
}
public static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n) {
int[] res = new int[n];
for(int i=0;i<n;i++) res[i] = nextInt();
return res;
}
long[] readLongArray(int n) {
long[] res = new long[n];
for(int i=0;i<n;i++) res[i] = nextLong();
return res;
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | a6fa0a29364b73d8d6ee5ceb64b12d47 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.Scanner;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
public class factorial {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
int tt = in.nextInt();
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
for(int w = 0; w<tt; w++) {
long n = in.nextLong();
long fact = 1;
ArrayList<Long> ar = new ArrayList<>();
for(int i = 1; i<=n; i++) {
fact = fact*i;
if(fact>n) {
break;
}
ar.add(fact);
}
int ans = Integer.MAX_VALUE;
for(int i = 0; i< (1<<ar.size()); i++) {
long s = n;
for(int h = 0; h<ar.size(); h++) {
if((i&(1<<h))!=0) {
s-=ar.get(h);
}
if(s<0) {
continue;
}
int k = Integer.bitCount(i)+Long.bitCount(s);
ans = Math.min(ans, k);
}
}
log.write(ans+"\n");
log.flush();
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 90049aa480786c0b6608c41b869ccb79 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | //Utilities
import java.io.*;
import java.util.*;
public class a {
static int t;
static long n;
static final long maxn = (long)1e12;
static ArrayList<Long> arrPow, arrFac;
static HashMap<Long, Integer> facMap;
static int sz;
static long min;
public static void main(String[] args) throws IOException {
arrPow = new ArrayList<Long>();
long tmp = 1;
while (tmp <= maxn) {
arrPow.add(tmp);
tmp *= 2;
}
arrFac = new ArrayList<Long>();
tmp = 1; long mul = 2;
while (tmp <= maxn) {
arrFac.add(tmp);
tmp *= mul;
mul++;
}
facMap = new HashMap<Long, Integer>();
sz = arrFac.size();
for (int i = 0; i < 1 << sz; i++) {
long add = 0; int cnt = 0;
for (int j = 0; j < sz; j++) {
if ((i & (1 << j)) > 0) {
add += arrFac.get(j);
cnt++;
}
}
if (!facMap.containsKey(add)) facMap.put(add, cnt);
else facMap.put(add, Math.min(facMap.get(add), cnt));
}
t = in.iscan();
while (t-- > 0) {
n = in.lscan();
min = Long.bitCount(n);
for (Map.Entry<Long, Integer> entry : facMap.entrySet()) {
long v = entry.getKey(), cnt = entry.getValue();
if (v > n) continue;
long toAdd = n - v;
cnt += Long.bitCount(toAdd);
min = Math.min(min, cnt);
}
out.println(min != Long.MAX_VALUE ? min : -1);
}
out.close();
}
static INPUT in = new INPUT(System.in);
static PrintWriter out = new PrintWriter(System.out);
private static class INPUT {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public INPUT (InputStream stream) {
this.stream = stream;
}
public INPUT (String file) throws IOException {
this.stream = new FileInputStream (file);
}
public int cscan () throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read (buf);
}
if (numChars == -1)
return numChars;
return buf[curChar++];
}
public int iscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
int res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public String sscan () throws IOException {
int c = cscan ();
while (space (c))
c = cscan ();
StringBuilder res = new StringBuilder ();
do {
res.appendCodePoint (c);
c = cscan ();
}
while (!space (c));
return res.toString ();
}
public double dscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
double res = 0;
while (!space (c) && c != '.') {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
res *= 10;
res += c - '0';
c = cscan ();
}
if (c == '.') {
c = cscan ();
double m = 1;
while (!space (c)) {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
m /= 10;
res += (c - '0') * m;
c = cscan ();
}
}
return res * sgn;
}
public long lscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
long res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public boolean space (int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
public static class UTILITIES {
static final double EPS = 10e-6;
public static void sort(int[] a, boolean increasing) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(long[] a, boolean increasing) {
ArrayList<Long> arr = new ArrayList<Long>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(double[] a, boolean increasing) {
ArrayList<Double> arr = new ArrayList<Double>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static int lower_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static void updateMap(HashMap<Integer, Integer> map, int key, int v) {
if (!map.containsKey(key)) {
map.put(key, v);
}
else {
map.put(key, map.get(key) + v);
}
if (map.get(key) == 0) {
map.remove(key);
}
}
public static long gcd (long a, long b) {
return b == 0 ? a : gcd (b, a % b);
}
public static long lcm (long a, long b) {
return a * b / gcd (a, b);
}
public static long fast_pow_mod (long b, long x, int mod) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod;
return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod;
}
public static long fast_pow (long b, long x) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow (b * b, x / 2);
return b * fast_pow (b * b, x / 2);
}
public static long choose (long n, long k) {
k = Math.min (k, n - k);
long val = 1;
for (int i = 0; i < k; ++i)
val = val * (n - i) / (i + 1);
return val;
}
public static long permute (int n, int k) {
if (n < k) return 0;
long val = 1;
for (int i = 0; i < k; ++i)
val = (val * (n - i));
return val;
}
// start of permutation and lower/upper bound template
public static void nextPermutation(int[] nums) {
//find first decreasing digit
int mark = -1;
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
mark = i - 1;
break;
}
}
if (mark == -1) {
reverse(nums, 0, nums.length - 1);
return;
}
int idx = nums.length-1;
for (int i = nums.length-1; i >= mark+1; i--) {
if (nums[i] > nums[mark]) {
idx = i;
break;
}
}
swap(nums, mark, idx);
reverse(nums, mark + 1, nums.length - 1);
}
public static void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void reverse(int[] nums, int i, int j) {
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
static int lower_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= cmp) high = mid;
else low = mid + 1;
}
return low;
}
static int upper_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > cmp) high = mid;
else low = mid + 1;
}
return low;
}
// end of permutation and lower/upper bound template
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | a5e8d6c756faeb1dbd957a0880fbb1fe | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | //Utilities
import java.io.*;
import java.util.*;
public class a {
static int t;
static long n;
static final long maxn = (long)1e12;
static ArrayList<Long> arrPow, arrFac;
static HashMap<Long, Integer> facMap;
static int sz;
static long min;
public static void main(String[] args) throws IOException {
arrPow = new ArrayList<Long>();
long tmp = 1;
while (tmp <= maxn) {
arrPow.add(tmp);
tmp *= 2;
}
arrFac = new ArrayList<Long>();
tmp = 1; long mul = 2;
while (tmp <= maxn) {
arrFac.add(tmp);
tmp *= mul;
mul++;
}
facMap = new HashMap<Long, Integer>();
sz = arrFac.size();
for (int i = 0; i < 1 << sz; i++) {
long add = 0; int cnt = 0;
for (int j = 0; j < sz; j++) {
if ((i & (1 << j)) > 0) {
add += arrFac.get(j);
cnt++;
}
}
if (!facMap.containsKey(add)) facMap.put(add, cnt);
else facMap.put(add, Math.min(facMap.get(add), cnt));
}
t = in.iscan();
while (t-- > 0) {
n = in.lscan();
min = Long.MAX_VALUE;
for (Map.Entry<Long, Integer> entry : facMap.entrySet()) {
long v = entry.getKey(), cnt = entry.getValue();
if (v > n) continue;
long toAdd = n - v;
cnt += Long.bitCount(toAdd);
min = Math.min(min, cnt);
}
out.println(min != Long.MAX_VALUE ? min : -1);
}
out.close();
}
static INPUT in = new INPUT(System.in);
static PrintWriter out = new PrintWriter(System.out);
private static class INPUT {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public INPUT (InputStream stream) {
this.stream = stream;
}
public INPUT (String file) throws IOException {
this.stream = new FileInputStream (file);
}
public int cscan () throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read (buf);
}
if (numChars == -1)
return numChars;
return buf[curChar++];
}
public int iscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
int res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public String sscan () throws IOException {
int c = cscan ();
while (space (c))
c = cscan ();
StringBuilder res = new StringBuilder ();
do {
res.appendCodePoint (c);
c = cscan ();
}
while (!space (c));
return res.toString ();
}
public double dscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
double res = 0;
while (!space (c) && c != '.') {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
res *= 10;
res += c - '0';
c = cscan ();
}
if (c == '.') {
c = cscan ();
double m = 1;
while (!space (c)) {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
m /= 10;
res += (c - '0') * m;
c = cscan ();
}
}
return res * sgn;
}
public long lscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
long res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public boolean space (int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
public static class UTILITIES {
static final double EPS = 10e-6;
public static void sort(int[] a, boolean increasing) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(long[] a, boolean increasing) {
ArrayList<Long> arr = new ArrayList<Long>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(double[] a, boolean increasing) {
ArrayList<Double> arr = new ArrayList<Double>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static int lower_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static void updateMap(HashMap<Integer, Integer> map, int key, int v) {
if (!map.containsKey(key)) {
map.put(key, v);
}
else {
map.put(key, map.get(key) + v);
}
if (map.get(key) == 0) {
map.remove(key);
}
}
public static long gcd (long a, long b) {
return b == 0 ? a : gcd (b, a % b);
}
public static long lcm (long a, long b) {
return a * b / gcd (a, b);
}
public static long fast_pow_mod (long b, long x, int mod) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod;
return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod;
}
public static long fast_pow (long b, long x) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow (b * b, x / 2);
return b * fast_pow (b * b, x / 2);
}
public static long choose (long n, long k) {
k = Math.min (k, n - k);
long val = 1;
for (int i = 0; i < k; ++i)
val = val * (n - i) / (i + 1);
return val;
}
public static long permute (int n, int k) {
if (n < k) return 0;
long val = 1;
for (int i = 0; i < k; ++i)
val = (val * (n - i));
return val;
}
// start of permutation and lower/upper bound template
public static void nextPermutation(int[] nums) {
//find first decreasing digit
int mark = -1;
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
mark = i - 1;
break;
}
}
if (mark == -1) {
reverse(nums, 0, nums.length - 1);
return;
}
int idx = nums.length-1;
for (int i = nums.length-1; i >= mark+1; i--) {
if (nums[i] > nums[mark]) {
idx = i;
break;
}
}
swap(nums, mark, idx);
reverse(nums, mark + 1, nums.length - 1);
}
public static void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void reverse(int[] nums, int i, int j) {
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
static int lower_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= cmp) high = mid;
else low = mid + 1;
}
return low;
}
static int upper_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > cmp) high = mid;
else low = mid + 1;
}
return low;
}
// end of permutation and lower/upper bound template
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 7bd8b832216ae6d4b561d14bfdae6076 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class FactorialsandPowersofTwo {
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException ignored) {}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
public static void main(String[] args){
FastScanner sc = new FastScanner();
// long mod = 1_000_000_007L;
// long mod = 998_244_353L;
long nmax = Math.round(Math.pow(10,12));
ArrayList<Long> f = new ArrayList<>();
long f1 = 6L;
long x = 3L;
while ( f1<=nmax ) {
f.add(f1);
x++;
f1 *= x;
}
int t = sc.nextInt();
for ( int zzz=0; zzz<t; zzz++ ) {
long n = sc.nextLong();
int ans = 100;
for ( int i=0; i<1<<f.size(); i++ ) {
long fs = 0L;
int fc = 0;
int i1 = i;
for ( int j=0; j<f.size(); j++ ) {
if ( i1%2==1 ) {
fs += f.get(j);
fc++;
}
i1 /= 2;
}
if ( fs>n ) continue;
long r = n-fs;
int rc = 0;
while ( r>0 ) {
if ( r%2L==1L ) rc++;
r /= 2L;
}
ans = Math.min(ans, fc+rc);
}
System.out.println(ans);
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 58769a98213c1b32f6ba98c2ea2cb96c | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.Scanner;
import java.util.*;
public class Main {
public static void main(String[] args) {
var sc = new Scanner(System.in);
int n = Integer.parseInt(sc.next());
long max = (long) (1e12);
List<Long> f = new ArrayList();
long fact = 6;
int i = 3;
while (fact < max) {
f.add(fact);
fact *= ++i;
}
long dp[] = new long[1 << f.size()];
for (i = 1; i < dp.length; i++) {
int fb = firstbit(i);
dp[i] = f.get(fb) + dp[i ^ (1 << fb)];
}
for (i = 0; i < n; i++) {
Long num = Long.parseLong(sc.next());
int min = 999;
for (int j = 0; j < dp.length; j++) {
if (dp[j] > num) break;
min = Math.min(min, countbit(j) + countbit(num - dp[j]));
}
System.out.println(min);
}
}
public static int countbit(long n) {
int count = 0;
for (int i = 0; i < 64; i++) {
if (((1L << i) & n) != 0) count++;
}
return count;
}
public static int firstbit(int n) {
for (int i = 31; i >= 0; i--) {
if (((1 << i) & n) != 0) return i;
}
return -1;
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | ba329b8cc212f295c825231deb684eb7 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.Scanner;
import java.util.*;
public class Main {
public static void main(String[] args) {
long max = (long) 1e12;
var sc = new Scanner(System.in);
int a = Integer.parseInt(sc.next());
List<Long> fact = new ArrayList();
for (long i = 3, factorial = 2; factorial < max; i++) {
factorial *= i;
fact.add(factorial);
}
int len = (1 << fact.size()) - 1;
long[] dp = new long[len];
for (int i = 1; i < len; i++) {
int fb = firstbit(i);
dp[i] = fact.get(fb) + dp[i - (1 << fb)];
}
for (int i = 0; i < a; i++) {
int min = 9999;
long n = Long.parseLong(sc.next());
for (int j = 0; j < len; j++) {
if (dp[j] <= n) {
min = Math.min(min, bitcount(n - dp[j]) + bitcount(j));
}
}
System.out.println(min);
}
}
public static int bitcount(long n) {
int count = 0;
for (int i = 0; i < 64; i++) {
if (((1L << i) & n) != 0) count++;
}
return count;
}
public static int firstbit(int n) {
for (int i = 31; i >= 0; i--) {
if (((1 << i) & n) != 0) return i;
}
return -1;
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 047a96a32c15e624c799fb3424d0cac4 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class JaiShreeRam{
static Scanner in=new Scanner();
static long systemTime;
static long mod = 1000000007;
static ArrayList<ArrayList<Integer>> adj;
static int seive[]=new int[1000001];
static long C[][];
static ArrayList<Integer> ans=new ArrayList<>();
public static void main(String[] args) throws Exception{
int z=in.readInt();
TreeSet<Long> st=new TreeSet<>();
long max=(long)1e12;
long k=1;
long c=2;
while(k<=max) {
st.add(k);
k*=c;
c++;
}
ArrayList<Long> al=new ArrayList<>();
al.addAll(st);
for(int test=1;test<=z;test++) {
//setTime();
solve(al);
//printTime();
//printMemory();
}
}
static void solve(ArrayList<Long> al) {
long n=in.readLong();
print(ans(0,n,al));
}
static int ans(int i,long sum,ArrayList<Long> al) {
if(i==al.size()) {
return cnt1(sum);
}
int ans=ans(i+1,sum,al);
if(sum-al.get(i)>=0) {
ans=Math.min(ans, 1+ans(i+1,sum-al.get(i),al));
}
return ans;
}
static int cnt1(long n) {
int cnt=0;
while(n>0) {
cnt+=n%2;
n/=2;
}
return cnt;
}
static long pow(long n, long m) {
if(m==0)
return 1;
else if(m==1)
return n;
else {
long r=pow(n,m/2);
if(m%2==0)
return (r*r)%mod;
else
return (r*r*n)%mod;
}
}
static long maxsumsub(ArrayList<Long> al) {
long max=0;
long sum=0;
for(int i=0;i<al.size();i++) {
sum+=al.get(i);
if(sum<0) {
sum=0;
}
max=Math.max(max,sum);
}
return max;
}
static long abs(long a) {
return Math.abs(a);
}
static void ncr(int n, int k){
C= new long[n + 1][k + 1];
int i, j;
for (i = 0; i <= n; i++) {
for (j = 0; j <= Math.min(i, k); j++) {
if (j == 0 || j == i)
C[i][j] = 1;
else
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
}
}
}
static boolean isPalin(String s) {
int i=0,j=s.length()-1;
while(i<=j) {
if(s.charAt(i)!=s.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
static int knapsack(int W, int wt[],int val[], int n){
int []dp = new int[W + 1];
for (int i = 1; i < n + 1; i++) {
for (int w = W; w >= 0; w--) {
if (wt[i - 1] <= w) {
dp[w] = Math.max(dp[w],dp[w - wt[i - 1]] + val[i - 1]);
}
}
}
return dp[W];
}
static void seive() {
Arrays.fill(seive, 1);
seive[0]=0;
seive[1]=0;
for(int i=2;i*i<1000001;i++) {
if(seive[i]==1) {
for(int j=i*i;j<1000001;j+=i) {
if(seive[j]==1) {
seive[j]=0;
}
}
}
}
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a)
l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++)
a[i]=l.get(i);
}
static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a)
l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++)
a[i]=l.get(i);
}
static int[] nia(int n){
int[] arr= new int[n];
int i=0;
while(i<n){
arr[i++]=in.readInt();
}
return arr;
}
static long[] nla(int n){
long[] arr= new long[n];
int i=0;
while(i<n){
arr[i++]=in.readLong();
}
return arr;
}
static int[] nia1(int n){
int[] arr= new int[n+1];
int i=1;
while(i<=n){
arr[i++]=in.readInt();
}
return arr;
}
static Integer[] nIa(int n){
Integer[] arr= new Integer[n];
int i=0;
while(i<n){
arr[i++]=in.readInt();
}
return arr;
}
static Long[] nLa(int n){
Long[] arr= new Long[n];
int i=0;
while(i<n){
arr[i++]=in.readLong();
}
return arr;
}
static long gcd(long a, long b) {
if (b==0) return a;
return gcd(b, a%b);
}
static void print(long i) {
System.out.println(i);
}
static void print(Object o) {
System.out.println(o);
}
static void print(int a[]) {
for(int i:a) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(long a[]) {
for(long i:a) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(ArrayList<Long> a) {
for(long i:a) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(Object a[]) {
for(Object i:a) {
System.out.print(i+" ");
}
System.out.println();
}
static void setTime() {
systemTime = System.currentTimeMillis();
}
static void printTime() {
System.err.println("Time consumed: " + (System.currentTimeMillis() - systemTime));
}
static void printMemory() {
System.err.println("Memory consumed: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000 + "kb");
}
static class Scanner{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String readString() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
double readDouble() {
return Double.parseDouble(readString());
}
int readInt() {
return Integer.parseInt(readString());
}
long readLong() {
return Long.parseLong(readString());
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 2ac53c9cd4e983e3641e4248ea6b8e0d | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Codechef {
static boolean multipleTC = true;
final static int Mod = 1000000007;
final static int Mod2 = 998244353;
final double PI = 3.14159265358979323846;
int MAX = 1000000007;
void pre() throws Exception {
}
long cntBit(long n){
if (n == 0)
return 0;
else
return (n & 1) + cntBit(n >> 1);
}
void solve(int t) throws Exception {
long n = nl();
long fact[] = new long[15];
fact[1] = 1;
for(int i=2;i<=14;i++)
fact[i] = fact[i-1]*i;
long ans = Long.MAX_VALUE;
for(long i=0;i<(1<<15);i++) {
long sum = 0;
for(int j=0;j<=14;j++) {
if((i & (1L<<j)) != 0)
sum += fact[j];
}
if(sum <= n)
ans = Math.min(ans, (Long.bitCount(i) + Long.bitCount(n-sum)));
}
pn(ans);
}
double dist(int x1, int y1, int x2, int y2) {
double a = x1 - x2, b = y1 - y2;
return Math.sqrt((a * a) + (b * b));
}
int[] readArr(int n) throws Exception {
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = ni();
}
return arr;
}
void sort(int arr[], int left, int right) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = left; i <= right; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = left; i <= right; i++)
arr[i] = list.get(i - left);
}
void sort(int arr[]) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < arr.length; i++)
arr[i] = list.get(i);
}
public long max(long... arr) {
long max = arr[0];
for (long itr : arr)
max = Math.max(max, itr);
return max;
}
public int max(int... arr) {
int max = arr[0];
for (int itr : arr)
max = Math.max(max, itr);
return max;
}
public long min(long... arr) {
long min = arr[0];
for (long itr : arr)
min = Math.min(min, itr);
return min;
}
public int min(int... arr) {
int min = arr[0];
for (int itr : arr)
min = Math.min(min, itr);
return min;
}
public long sum(long... arr) {
long sum = 0;
for (long itr : arr)
sum += itr;
return sum;
}
public long sum(int... arr) {
long sum = 0;
for (int itr : arr)
sum += itr;
return sum;
}
String bin(long n) {
return Long.toBinaryString(n);
}
String bin(int n) {
return Integer.toBinaryString(n);
}
static int bitCount(int x) {
return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
}
static void dbg(Object... o) {
System.err.println(Arrays.deepToString(o));
}
int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
int abs(int a) {
return (a < 0) ? -a : a;
}
long abs(long a) {
return (a < 0) ? -a : a;
}
void p(Object o) {
out.print(o);
}
void pn(Object o) {
out.println(o);
}
void pni(Object o) {
out.println(o);
out.flush();
}
void pn(int[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
void pn(long[] arr) {
int n = arr.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(arr[i] + " ");
}
pn(sb);
}
String n() throws Exception {
return in.next();
}
String nln() throws Exception {
return in.nextLine();
}
int ni() throws Exception {
return Integer.parseInt(in.next());
}
long nl() throws Exception {
return Long.parseLong(in.next());
}
double nd() throws Exception {
return Double.parseDouble(in.next());
}
public static void main(String[] args) throws Exception {
new Codechef().run();
}
FastReader in;
PrintWriter out;
void run() throws Exception {
in = new FastReader();
out = new PrintWriter(System.out);
int T = (multipleTC) ? ni() : 1;
pre();
for (int t = 1; t <= T; t++)
solve(t);
out.flush();
out.close();
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception {
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 3af494689993813c3d07c057e02efe8e | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Set;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Stream;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CFactorialsAndPowersOfTwo solver = new CFactorialsAndPowersOfTwo();
solver.solve(1, in, out);
out.close();
}
static class CFactorialsAndPowersOfTwo {
long MAX = (long) 1e12;
int M = 100;
long[] sum;
public void solve(int testNumber, FastReader in, PrintWriter out) {
List<Long> list = new ArrayList<>();
Set<Long> set = new HashSet<>();
for (int i = 0; i < 60; i++) {
if ((1L << i) > MAX) break;
set.add((1L << i));
}
long tmp = 1;
for (int i = 1; ; i++) {
tmp *= i;
if (tmp > MAX) break;
set.add(tmp);
}
set.stream().forEach(key -> {
list.add(key);
});
list.sort(Comparator.reverseOrder());
sum = new long[list.size() + 1];
for (int i = list.size() - 1; i >= 0; i--) {
sum[i] = sum[i + 1] + list.get(i);
}
int t = in.nextInt();
while (t-- > 0) {
long n = in.nextLong();
int ans = dfs(list, 0, n, 0);
out.println(ans == M ? -1 : ans);
// int ans = 0;
// for (Long num : list) {
// if (n >= num) {
// n-=num;
// ans++;
// }
// }
// out.println(n == 0 ? ans : -1);
}
}
private int dfs(List<Long> list, int p, long n, int num) {
if (p >= list.size()) return n == 0 ? num : M;
if (n < 0) return M;
if (n == 0) return num;
if (sum[p] < n) return M;
int ans = dfs(list, p + 1, n - list.get(p), num + 1);
ans = Math.min(ans, dfs(list, p + 1, n, num));
return ans;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() {
while (st == null || (!st.hasMoreElements())) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | a877c663236850f81ead44240d9bd472 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | //package com.company;
import java.io.*;
import java.util.*;
public class Main {
public static List<Long> l;
public static class pair<T, E>{
T first;
E second;
pair(T first, E second){
this.first = first;
this.second = second;
}
void printPair(){
out.println(first + " " + second);
}
}
public static int numOfBits(long x){
int cnt = 0;
for(int i = 0; i < 63; i++){
if((x & (1L << i)) != 0){
cnt++;
}
}
return cnt;
}
public static List<pair<List<Long>, Long>> subs;
public static void StartCrushing() throws IOException {
long n = in.nextLong();
int ans = numOfBits(n);
for(pair<List<Long>, Long> e : subs){
if(e.second <= n){
ans = Math.min(ans, e.first.size() + numOfBits(n - e.second));
}
}
out.print(ans);
}
public static void main(String[] args) throws IOException {
openIO();
l = new ArrayList<>();
l.add(1L);
long i = 2;
while(l.get(l.size() - 1) <= (long)1e12){
l.add(l.get(l.size() - 1) * i++);
}
subs = new ArrayList<>();
for(i = 0; i < (1L << l.size()); i++){
long sum = 0;
List<Long> sub = new ArrayList<>();
for(int j = 0; j < l.size(); j++){
if((i & (1L << j)) != 0){
sub.add(l.get(j));
sum += l.get(j);
}
}
subs.add(new pair<>(sub, sum));
}
int t = 1;
t = in.nextInt();
while(t-- > 0){
StartCrushing();
if(t == 0)
break;
out.println();
}
closeIO();
}
static FastestReader in;
static PrintWriter out;
private static void openIO() throws IOException {
in = new FastestReader();
out = new PrintWriter(System.out);
}
public static void closeIO() throws IOException {
out.flush();
out.close();
in.close();
}
private static final class FastestReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastestReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastestReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private static boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {
}
return b;
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
final boolean neg = c == '-';
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | a925a4537ee3b7c9b804537bb892304a | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static FastReader f = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int t = f.nextInt();
pre();
while(t-- > 0) {
solve();
}
out.close();
}
private static long[] fact = new long[12];
private static void pre() {
long now = 6;
long cnt = 4;
for(int i=0;i<12;i++) {
fact[i] = now;
now *= cnt;
cnt++;
}
}
private static void solve() {
long n = f.nextLong();
int answer = Integer.MAX_VALUE;
for(int i=0;i<4096;i++) {
int j = i;
int curr = 0;
long ans = 0;
int ones = 0;
while (j > 0) {
if((j % 2) == 1) {
ans += fact[curr];
ones++;
}
j >>= 1;
curr++;
}
if(ans <= n) {
answer = Math.min(answer, calc(n-ans) + ones);
}
}
out.println(answer);
}
static int calc(long ones) {
int ans = 0;
while (ones > 0) {
if(ones % 2 == 1) {
ans++;
}
ones >>= 1;
}
return ans;
}
static class FastReader {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String next() {
while(st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch(IOException ioe) {
ioe.printStackTrace();
}
return s;
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | a91df1769c02d887c00877fc9f75fd20 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Ex extends PrintWriter{
Ex() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
Ex o = new Ex(); o.main(); o.flush();
}
int bitCount1(long n){
int ans=0;
while(n>0){
ans+=(n%2==0?0:1);
n>>=1;
}
return ans;
}
void main(){
Scanner sc = new Scanner(System.in);
long[] fc = new long[15];
fc[0]=1;
for(int i=1;i<15;i++)
fc[i] = fc[i-1]*(i+1);
int tc = sc.nextInt();
while(tc>0){
long n = sc.nextLong();
int ans=50;
for(int i=0;i<(1<<14);i++){
long sum=0;
int fcnt=0;
for(int j=0;j<14;j++){
if((i&(1<<j))>=1){
fcnt++;
sum+=fc[j];
}
}
if(sum>n) break;
int pcnt=bitCount1(n-sum);
ans = Math.min(pcnt+fcnt,ans);
}
println(ans);
tc--;
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 9def1c54001802ce90eade21c9399046 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | // package div_2_774;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class C{
public static void main(String[] args){
FastReader sc = new FastReader();
int t=sc.nextInt();
while(t-->0){
long n = sc.nextLong();
long[] fac = new long[15];
fac[0] = 1;
for (int i = 1; i <= 14; i++) {
fac[i] = fac[i - 1] * i;
}
int ans = 100;
for (int s = 0; s < (1 << 14); s++) {
long m = n;
for (int i = 0; i < 14; i++) {
if (((s >> i) & 1) > 0) {
m -= fac[i + 1];
}
}
if (m >= 0) {
ans = Math.min(ans, cnt_set_bit(s) + cnt_set_bit(m));
}
}
System.out.println(ans);
}
}
static int cnt_set_bit(long n) {
int cnt=0;
while(n>0) {
if((n&1)==1)cnt++;
n>>=1;
}
return cnt;
}
static int pow(int a,int b) {
if(b==0)return 1;
if(b==1)return a;
return a*pow(a,b-1);
}
static class pair {
long sum;int cnt;
pair(long sum,int cnt){
this.sum=sum;
this.cnt=cnt;
}
}
static ArrayList<Integer> primeFac(int n){
ArrayList<Integer>ans = new ArrayList<Integer>();
int lp[]=new int [n+1];
Arrays.fill(lp, 0); //0-prime
for(int i=2;i<=n;i++) {
if(lp[i]==0) {
for(int j=i;j<=n;j+=i) {
if(lp[j]==0) lp[j]=i;
}
}
}
int fac=n;
while(fac>1) {
ans.add(lp[fac]);
fac=fac/lp[fac];
}
print(ans);
return ans;
}
static ArrayList<Long> prime_in_given_range(long l,long r){
ArrayList<Long> ans= new ArrayList<>();
int n=(int)Math.sqrt(r)+1;
int prime[]=sieve_of_Eratosthenes(n);
long res[]=new long [(int)(r-l)+1];
for(int i=0;i<=r-l;i++) {
res[i]=i+l;
}
for(int i=0;i<prime.length;i++) {
if(prime[i]==1) {
System.out.println(2);
for(int j=Math.max((int)i*i, (int)(l+i-1)/i*i);j<=r;j+=i) {
res[j-(int)l]=0;
}
}
}
for(long i:res) if(i!=0)ans.add(i);
return ans;
}
static int [] sieve_of_Eratosthenes(int n) {
int prime[]=new int [n];
Arrays.fill(prime, 1); // 1-prime | 0-not prime
prime[0]=prime[1]=0;
for(int i=2;i<n;i++) {
if(prime[i]==1) {
for(int j=i*i;j<n;j+=i) {
prime[j]=0;
}
}
}
return prime;
}
static long binpow(long a,long b) {
long res=1;
if(b==0)return 1;
if(a==0)return 0;
while(b>0) {
if((b&1)==1) {
res*=a;
}
a*=a;
b>>=1;
}
return res;
}
static void print(int a[]) {
System.out.println(a.length);
for(int i:a) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(long a[]) {
System.out.println(a.length);
for(long i:a) {
System.out.print(i+" ");
}
System.out.println();
}
static long rolling_hashcode(String s ,int st,int end,long Hashcode,int n) {
if(end>=s.length()) return -1;
int mod=1000000007;
Hashcode=Hashcode-(s.charAt(st-1)*(long)Math.pow(27,n-1));
Hashcode*=10;
Hashcode=(Hashcode+(long)s.charAt(end))%mod;
return Hashcode;
}
static long hashcode(String s,int n) {
long code=0;
for(int i=0;i<n;i++) {
code+=((long)s.charAt(i)*(long)Math.pow(27, n-i-1)%1000000007);
}
return code;
}
static void print(ArrayList<Integer> a) {
System.out.println(a.size());
for(long i:a) {
System.out.print(i+" ");
}
System.out.println();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
int [] fastArray(int n) {
int a[]=new int [n];
for(int i=0;i<n;i++) {
a[i]=nextInt();
}
return a;
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | d1d912152840c3ad49451d80af3c288b | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
//-------------------------------///////////////****/////////******//////////
//------------------------------------///**********//*****//********//*****//
//-----------------------------------///**********//*****//********//*****//
//----------------------------------///**********//*****//********//*****//
//---------------------------------///**********//*****//********//*****//
//--------------------------------///**********//*****//********//*****//
//--------------------------///**///**********//*****//********//*****//
//---------------------------/////***********/////////*******//////////
public class CodeForces {
final static String no = "NO";
final static String yes = "YES";
static long count = 0;
static public OutputWriter w = new OutputWriter(System.out);
static public FastScanner sc = new FastScanner();
static HashMap<Integer, Integer> map = new HashMap<>();
static Scanner fc = new Scanner(System.in);
//*******************************************Be SANSA***********************************
//************************************Don't stick to single approach********************
//*****************************************You are a slow learner But you learn*********
//***************************************Don't fall in rating trap**********************
//**********************************Pain in temporary, regret remains forever***********
////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
long []pre= new long[16];
pre[0] = 1;
for(int i=1;i<pre.length;i++) {
pre[i] = pre[i-1]*i;
}
int t = sc.nextInt();
while(t-->0) {
long n = sc.nextLong();
long all = (1<<pre.length);
int r = Long.bitCount(n);
for(int i=0;i<all;i++) {
long sum =0 ;
for(int j = 0;j<16;j++) {
if(((1<<j) & i)==0) {
continue;
}
sum += pre[j];
}
if(sum>n) {
continue ;
}
r = Integer.min((int) r,(Long.bitCount(n-sum) + Integer.bitCount(i)));
}
w.writer.println(r);
}
w.writer.flush();
}
//////////////////////////////////////////////////////////////////////////////////////////
static ArrayList<Integer> primes = new ArrayList<>();
static boolean[]sieve = new boolean[(int)1e5+1];
static void sieve(int n) {
sieve[0] = sieve[1] = true;
primes.add(2);
for(int i=3;i<=(int)n;i+=2) {
if(!sieve[i]) {
primes.add(i);
for(int j=i*2;j<=(int)n;j+=i) {
sieve[j]= true;
}
}
}
}
static int floorPowerOf2(int n) {
int p = (int)(Math.log(n) /
Math.log(2));
return (int)Math.pow(2, p);
}
static int ceilPowerOf2(int n) {
int p = (int)(Math.log(n) /
Math.log(2));
return (int)Math.pow(2, p+1);
}
static int[] reverseArray(int[] arr, int begin, int end) {
if (arr.length == 1) {
return arr;
}
while (begin < end) {
int tmp = arr[begin];
arr[begin++] = arr[end];
arr[end--] = tmp;
}
return arr;
}
static String reverse(String s) {
return new StringBuilder(s).reverse().toString();
}
static int printCubes(int a, int b) {
// Find cube root of both a and b
int acrt = (int) Math.cbrt(a);
int bcrt = (int) Math.cbrt(b);
int cnt = 0;
// Print cubes between acrt and bcrt
for (int i = acrt; i <= bcrt; i++)
if (i * i * i >= a && i * i * i <= b && !(checkPerfectSquare(i)))
cnt++;
return cnt;
}
static double countSquares(int a, int b) {
return (Math.floor(Math.sqrt(b)) - Math.ceil(Math.sqrt(a)) + 1);
}
static boolean checkPerfectSquare(int n) {
// If ceil and floor are equal
// the number is a perfect
// square
if (Math.ceil((double) Math.sqrt(n)) == Math.floor((double) Math.sqrt(n))) {
return true;
} else {
return false;
}
}
static boolean perfectCube(int N) {
int cube_root;
cube_root = (int) Math.round(Math.cbrt(N));
// If cube of cube_root is equals to N,
// then print Yes Else print No
if (cube_root * cube_root * cube_root == N) {
//System.out.println("Yes");
return true;
} else {
// System.out.println("NO");
return false;
}
}
static List<Integer> printDivisors(int n) {
// Note that this loop runs till square root
List<Integer> sl = new ArrayList<>();
for (int i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
// If divisors are equal, print only one
if (n / i == i)
sl.add(i);
else // Otherwise print both
{
sl.add(i);
sl.add(n / i);
}
}
}
return sl;
}
static boolean isPrime(int n) {
if (n <= 1)
return false;
else if (n == 2)
return true;
else if (n % 2 == 0)
return false;
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
return true;
}
static class Pair {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
static public boolean checkBit(int n, int i) {
if ((n >> i & 1) == 1) {
return true;
} else {
return false;
}
}
static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static boolean isPowerOfTwo(long n) {
if (n == 0)
return false;
return (long) (Math.ceil((Math.log(n) / Math.log(2)))) == (long) (Math.floor(((Math.log(n) / Math.log(2)))));
}
// method to return LCM of two numbers
static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
static long getPairsCount(long[] arr, long sum) {
Map<Long, Long> hm = new HashMap<>();
int n = arr.length;
long count = 0;
for (int i = 0; i < n; i++) {
if (hm.containsKey(sum - arr[i])) {
count += hm.get(sum - arr[i]);
}
if (hm.get(arr[i]) != null) {
hm.put(arr[i], hm.get(arr[i]) + 1);
} else {
hm.put(arr[i], 1l);
}
}
return count;
}
static boolean isEqualList(ArrayList<Integer> arr, ArrayList<Integer> temp) {
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i) != temp.get(i)) {
return true;
}
}
return false;
}
static void sort(int[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i)
continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
}
static void sort(long[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i)
continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
}
static String mulStr(String s,int n) {
StringBuilder sv = new StringBuilder();
for(int i=0;i<n;i++) {
sv.append(s);
}
return sv.toString();
}
static void sortDec(int[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i)
continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
int l = 0;
int r = n - 1;
while (l < r) {
arr[l] ^= arr[r];
arr[r] ^= arr[l];
arr[l] ^= arr[r];
l++;
r--;
}
}
static void sortDec(long[] arr) {
Random rand = new Random();
int n = arr.length;
for (int i = 0; i < n; i++) {
int idx = rand.nextInt(n);
if (idx == i)
continue;
arr[i] ^= arr[idx];
arr[idx] ^= arr[i];
arr[i] ^= arr[idx];
}
Arrays.sort(arr);
int l = 0;
int r = n - 1;
while (l < r) {
arr[l] ^= arr[r];
arr[r] ^= arr[l];
arr[l] ^= arr[r];
l++;
r--;
}
}
static int[] countInversions(int[] arr, int low, int high) {
if (low == high) {
int base[] = new int[1];
base[0] = arr[low];
return base;
}
int mid = low + (high - low) / 2;
int left[] = countInversions(arr, low, mid);
int right[] = countInversions(arr, mid + 1, high);
int[] merged = merge(left, right);
return merged;
}
static int[] merge(int first[], int[] next) {
int i = 0;
int j = 0;
int k = 0;
int[] merged = new int[first.length + next.length];
while (j < first.length && k < next.length) {
if (first[j] <= next[k]) {
merged[i++] = first[j++];
} else {
count += first.length - j;
merged[i++] = next[k++];
}
}
while (j < first.length) {
merged[i++] = first[j++];
}
while (k < next.length) {
merged[i++] = next[k++];
}
return merged;
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] longArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
}
static public class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | c3eef0d086dccbb699ca2b57b8b2b663 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Codeforces {
final static int mod = 1000000007;
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
int t = sc.nextInt();
long[] fact = new long[16];
fact[1] = 1;
for (int i = 2; i <= 15; i++) {
fact[i] = fact[i - 1] * i;
}
outer: while (t-- > 0) {
long n = sc.nextLong();
int ans = Integer.MAX_VALUE;
for (long mask = 0; mask < (1 << 15); mask++) {
long sum = 0;
long a = Long.bitCount(mask);
for (int i = 0; i <= 14; i++) {
if ((mask & (1L << i)) != 0) {
// System.out.println(mask + "-" + (1L << i));
sum += fact[i + 1];
}
}
if (sum <= n) {
long b = Long.bitCount(n - sum) + a;
ans = Math.min((int) b, ans);
}
}
System.out.println(ans);
}
}
static void sortLong(long[] a) // check for long
{
ArrayList<Long> l = new ArrayList<>();
for (long i : a)
l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++)
a[i] = l.get(i);
}
static void sortInt(int[] a) // check for int
{
ArrayList<Integer> l = new ArrayList<>();
for (int i : a)
l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++)
a[i] = l.get(i);
}
public static boolean isSorted(int[] nums, int n) {
for (int i = 1; i < n; i++) {
if (nums[i] < nums[i - 1])
return false;
}
return true;
}
public static boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i <= j) {
if (s.charAt(i) != s.charAt(j))
return false;
i++;
j--;
}
return true;
}
public static void sortByColumn(int arr[][], int col) {
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
// To sort in descending order revert
// the '>' Operator
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
});
}
public static void backtrack(String[] letters, int index, String digits, StringBuilder build, List<String> result) {
if (build.length() >= digits.length()) {
result.add(build.toString());
return;
}
char[] key = letters[digits.charAt(index) - '2'].toCharArray();
for (int j = 0; j < key.length; j++) {
build.append(key[j]);
backtrack(letters, index + 1, digits, build, result);
build.deleteCharAt(build.length() - 1);
}
}
public static String get(String s, int k) {
int n = s.length();
int rep = k % n == 0 ? k / n : k / n + 1;
s = s.repeat(rep);
return s.substring(0, k);
}
public static int diglen(Long y) {
int a = 0;
while (y != 0L) {
y /= 10;
a++;
}
return a;
}
static class FastReader {
BufferedReader br;
StringTokenizer st; // StringTokenizer() is used to read long strings
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public class Pair implements Comparable<Pair> {
public final int index;
public final int value;
public Pair(int index, int value) {
this.index = index;
this.value = value;
}
@Override
public int compareTo(Pair other) {
// multiplied to -1 as the author need descending sort order
return -1 * Integer.valueOf(this.value).compareTo(other.value);
}
}
static String reverseString(String str) {
StringBuilder input = new StringBuilder();
return input.append(str).reverse().toString();
}
static long factorial(int n, int b) {
if (n == b)
return 1;
return n * factorial(n - 1, b);
}
static int lcm(int ch, int b) {
return ch * b / gcd(ch, b);
}
static int gcd(int ch, int b) {
return b == 0 ? ch : gcd(b, ch % b);
}
static double ceil(double n, double k) {
return Math.ceil(n / k);
}
static int sqrt(double n) {
return (int) Math.sqrt(n);
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 10c0dab5bdcd7cd1f69bc3b0a4a28bf3 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | /*
_oo0oo_
o8888888o
88" . "88
(| -_- |)
0\ = /0
___/`---'\___
.' \\| |// '.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' |_/ |
\ .-\__ '-' ___/-. /
___'. .' /--.--\ `. .'___
."" '< `.___\_<|>_/___.' >' "".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `_. \_ __\ /__ _/ .-` / /
=====`-.____`.___ \_____/___.-`___.-'=====
`=---='
*/
import java.util.*;
import java.math.*;
import java.io.*;
import java.lang.Math.*;
public class KickStart2020 {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
public static class Pair implements Comparable<Pair> {
public int index;
public int value;
public Pair(int index, int value) {
this.index = index;
this.value = value;
}
@Override
public int compareTo(Pair other) {
// multiplied to -1 as the author need descending sort order
if(other.index < this.index) return 1;
if(other.index > this.index) return -1;
return 0;
}
@Override
public String toString() {
return this.index + " " + value;
}
}
static boolean isPrime(long d) {
if(d == 0) return true;
if (d == 1)
return false;
for (int i = 2; i <= (long) Math.sqrt(d); i++) {
if (d % i == 0)
return false;
}
return true;
}
static int decimalTob(long n, int k , int count) {
long x = n % k;
long y = n / k;
count += x;
if(y > 0) {
count = decimalTob(y, k, count);
}
return count;
}
static long powermod(long x, long y, long mod) {
if(y == 0) return 1;
long value = powermod(x, y / 2, mod);
if(y % 2 == 0) return (value * value) % mod;
return (value * (value * x) % mod) % mod;
}
static long power(long x, long y) {
if(y == 0) return 1;
long value = power(x, y / 2);
if(y % 2 == 0) return (value * value);
return value * value * x;
}
static int bS(int l, int r, int find, int arr[]) {
if(r < l) return l;
int mid = (l + r) / 2;
if(arr[mid] >= find) return bS(l, mid - 1, find, arr);
return bS(mid + 1, r, find, arr);
}
static int dp(long n, int index, long arr[]) {
if(index == 0) {
return decimalTob(n, 2, 0);
}
int notake = dp(n, index - 1, arr);
int take = Integer.MAX_VALUE;
if(n >= arr[index]) take = 1 + dp(n - arr[index], index - 1, arr);
return Math.min(take, notake);
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = sc.nextInt();
outerloop:
while(t-- > 0) {
long n = sc.nextLong();
long arr[] = new long[15];
long count = 1;
for(int i = 1; i <= 14; i++) {
count *= i;
arr[i] = count;
}
out.println(dp(n, 14, arr));
}
out.close();
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | d14ff0a1c33da63d71b4a666431943bf | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static Scanner obj = new Scanner(System.in);
public static PrintWriter out = new PrintWriter(System.out);
public static int i() {
return obj.nextInt();
}
public static void main(String[] args) {
int len = i();
while (len-- != 0) {
long n=obj.nextLong();
Vector<Long> v=new Vector<>();
long fac=6;
for(int i=4;true;i++)
{
if(fac>n)break;
v.add(fac);
fac=fac*i;
}
long ans=Integer.MAX_VALUE;
for(int mask=0;mask<(1<<v.size());mask++)
{
long sum=n;
for(int i=0;i<v.size();i++) if((mask&(1<<i))!=0)sum-=v.get(i);
if(sum<0)continue;
int tut=Integer.bitCount(mask)+Long.bitCount(sum);
ans=Math.min(ans, tut);
}
out.println(ans);
}
out.flush();
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | b8acb765a843a82f5a08738331a01cc2 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Solution {
private final static FastReader scan = new FastReader();
static List<Integer> l1 = new ArrayList<>();
static HashMap<String,Integer> dp = new HashMap<>();
public static void main(String[] args) {
int tc = 1;
tc = scan.nextInt();
while(tc--!=0)
solve();
}
private static void solve() {
dp = new HashMap<>();
long n = scan.nextLong();
long[] fact = new long[20];
long[] power = new long[40];
List<Long> out = new ArrayList<>();
HashSet<Long> st = new HashSet<>();
for(int i = 0;i<15;i++) {
fact[i] = fact(i);
if(fact[i]!=0) {
if(!st.contains(fact[i])) {
out.add(fact[i]);
st.add(fact[i]);
}
}
}
Collections.sort(out);
//System.out.print(out+"");
long[] a = new long[out.size()];
for(int i = 0;i<a.length;i++) {
a[i] = out.get(i);
}
System.out.println(dp(0,n,0,a));
}
private static int dp(long cSum, long Ssum,int l,long[] a) {
if(cSum>Ssum) {
return 99999;
}
if(l==a.length) {
long vakForMask = Ssum -cSum;
if(cSum==Ssum) {
return 0;
}
if(cSum<Ssum) {
int coutn = setBits(vakForMask);
return coutn;
}
return 99999;
}
return Math.min(dp(cSum+a[l],Ssum,(l+1),a)+1,dp(cSum,Ssum,(l+1),a));
}
private static int setBits(long n) {
long mask = 1;
int count = 0;
for(int i = 0;i<60;i++) {
if((n&mask) == mask) {
count++;
}
mask = mask<<1;
}
return count;
}
private static long fact(long u) {
if(u ==0) return 1l;
return u*fact(u-1);
}
private static long power(long u) {
if(u ==0) return 1l;
return 2*power(u-1);
}
@SuppressWarnings("unused")
private static void ptArr(final int[] a) {
for (int i : a) System.out.print(i + " ");
System.out.println();
}
@SuppressWarnings("unused")
private static void pt2DArr(final int[][] a) {
for(int[] j:a) {
for (int i : j) System.out.print(i + " ");
System.out.println();
}
System.out.println();
}
@SuppressWarnings("unused")
private static void pt(String val) {
System.out.print(val);
}
@SuppressWarnings("unused")
private static void pln(String val) {
System.out.println(val);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static class ArrayHash {
int[] a;
ArrayHash(int[] a) {
this.a = Arrays.copyOf(a, a.length);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(a);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ArrayHash other = (ArrayHash) obj;
return Arrays.equals(a, other.a);
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | e01ca76e66e2728de7987713d04ed2f3 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.*;
import java.math.*;
public class C_Factorials_and_Powers_of_Two{
public static void main (String[] args){
try (Scanner s = new Scanner(System.in)) {
StringBuilder sb=new StringBuilder();
int t=1;t=s.nextInt();
for(int test=1;test<=t;test++){
long n=s.nextLong();
long ans=0,sum=0;boolean good=true;
// long[] a=new long[n];
// for(int i=0;i<n;i++)a[i]=s.nextLong();
// String S=s.nextLine();char a[]=S.toCharArray();
ArrayList<Long> factorials = new ArrayList<>();
long prod = 2;
for (int i = 3; prod <=n; i++) {
prod *= i;
factorials.add(prod);
}
ans = Integer.MAX_VALUE;
// System.out.println(factorials);
for (int mask = 0; mask < (1 << factorials.size()); mask++) {
sum = n;
for (int i = 0; i < factorials.size(); i++) {
if (((1 << i) & mask) != 0)
sum -= factorials.get(i);
}
if (sum >=0)
ans = Math.min(ans, Integer.bitCount(mask) + Long.bitCount(sum));
}
// System.out.println(ans);
sb.append(ans).append("\n");
}
System.out.println(sb);
}
}
static void pArray(long[] a){
int n=a.length;
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | fbb36d6d5eef4025f0c9372477f5df11 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes |
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.Math.PI;
import static java.lang.Math.min;
import static java.lang.System.arraycopy;
import static java.lang.System.exit;
import static java.util.Arrays.copyOf;
import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;
import java.io.FileReader;
import java.io.FileWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Comparator;
import java.lang.StringBuilder;
import java.util.Collections;
import java.util.*;
import java.text.DecimalFormat;
public class Solution {
static class Edge{
int u, v, w;
Edge(int u, int v, int w){
this.u = u;
this.v = v;
this.w = w;
}
}
static class Pair{
int first, second;
Pair(int first, int second){
this.first = first;
this.second = second;
}
}
static class Point{
int x, y;
Point(int x, int y){
this.x = x;
this.y = y;
}
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
static int dx[] = {-1,0,1,0};
static int dy[] = {0,-1,0,1};
private static void solve() throws IOException{
long n = scanLong();
long fact[] = new long[15];
fact[0] = 1;
for(int i = 1; i<15; ++i){
fact[i] = fact[i-1] * i;
}
int answer = Integer.MAX_VALUE;
for(int i = 0; i<(1<<15); ++i){
long sum = 0; int count = 0;
for(int j =0; j<15; ++j){
if((i&(1<<j))!=0){
sum+= fact[j];
++count;
}
}
answer = Math.min(answer, (count+ones(n-sum)));
}
out.println(answer);
// out.println(ones(15));
// out.println(ones(256));
// out.println(ones(1023));
}
private static int ones(long n){
int count = 0;
for(int i = 41; i>=0; i--){
if((n &((long)1<<i))!=0){
++count;
}
}
return count;
}
private static int[] inputArray(int n) throws IOException {
int arr[] = new int[n];
for(int i=0; i<n; ++i)
arr[i] = scanInt();
return arr;
}
public static void main(String[] args) {
try {
long startTime = System.currentTimeMillis();
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
//in = new BufferedReader(new FileReader("input.txt"));
//out = new PrintWriter(new FileWriter("output.txt"));
int test=scanInt();
for(int t=1; t<=test; t++){
// out.print("Case #"+t+": ");
solve();
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
//out.println(totalTime+"---------- "+System.currentTimeMillis() );
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
static int scanInt() throws IOException {
return parseInt(scanString());
}
static long scanLong() throws IOException {
return parseLong(scanString());
}
static double scanDouble() throws IOException {
return parseDouble(scanString());
}
static String scanString() throws IOException {
if (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static String scanLine() throws IOException {
return in.readLine();
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 8a242a2c637b8bdc7a1bf968675ffebe | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes |
import java.util.*;
import java.math.*;
import java.io.*;
public class Solution {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static void sort(int a[]){ // int -> long
ArrayList<Integer> arr=new ArrayList<>(); // Integer -> Long
for(int i=0;i<a.length;i++)
arr.add(a[i]);
Collections.sort(arr);
for(int i=0;i<a.length;i++)
a[i]=arr.get(i);
}
private static long gcd(long a, long b){
if(b==0)return a;
return gcd(b,a%b);
}
private static long pow(long x,long y){
if(y==0)return 1;
long temp = pow(x, y/2);
if(y%2==1){
return x*temp*temp;
}
else{
return temp*temp;
}
}
static long powM(long a, long b) {
if (b == 0) return 1;
long res = pow(a, b / 2);
res = (res%mod * res%mod) % 1_000_000_007;
if (b % 2 == 1) {
res = (res%mod * a%mod) % 1_000_000_007;
}
return res%mod;
}
static int log(long n){
int res = 0;
while(n>0){
res++;
n/=2;
}
return res;
}
static int mod = (int)1e9+7;
static PrintWriter out;
static FastReader sc ;
public static void main(String[] args) throws IOException {
sc = new FastReader();
out = new PrintWriter(System.out);
// primes();
// ________________________________
StringBuilder output = new StringBuilder();
int test =sc.nextInt();
dp = new long[17];
long fact =1;
dp[1] =1;
dp[0] =1;
for(int i =2;i<17;i++)
{
dp[i] = i*dp[i-1];
}
while (test-- > 0) {
//System.out.println(mdh+" "+nhc);
long n = sc.nextLong();
solver(n);
}
// solver(s);
// int n = sc.nextInt();
// out.println(solver());
// ________________________________
out.flush();
}
static class Edge
{
int u, v;
Edge(int u, int v)
{
this.u = u;
this.v = v;
}
}
static class Pair implements Comparable <Pair>{
int l, r;
Pair(int l, int r)
{
this.l = l;
this.r = r;
}
public int compareTo(Pair o)
{
return this.l-o.l;
}
}
static long [] dp;
public static void solver( long n) {
int ans = Integer.MAX_VALUE;
for(int i =0;i<(1<<17);i++)
{
long sum =0;
for(int j =0;j<17;j++)
{
if((i&(1<<j))!=0)
{
sum+=dp[j];
}
}
if(sum>n)
break;
int temp =setbitcnt(i);
temp+=setbitcnt(n-sum);
//System.out.println(temp);
ans = Math.min(ans, temp);
}
System.out.println(ans);
}
public static int setbitcnt(long n)
{
int nb =0;
while(n!=0)
{
long rmsb = n&(-n);
n = n-rmsb;
nb++;
}
return nb;
}
public static long log2(long N)
{
// calculate log2 N indirectly
// using log() method
long result = (long)(Math.log(N) / Math.log(2));
return result;
}
static long highestPowerof2(long x)
{
// check for the set bits
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
// Then we remove all but the top bit by xor'ing the
// string of 1's with that string of 1's shifted one to
// the left, and we end up with just the one top bit
// followed by 0's.
return x ^ (x >> 1);
}
public
static void rotate(int [] arr, int s, int n)
{
int x = arr[n], i;
for (i = n; i > s; i--)
arr[i] = arr[i-1];
arr[s] = x;
// for(int j=s;j<=n;j++)
// System.out.print(arr[j]+" ");
// System.out.println();
}
static int lower_bound(int[] a , long x)
{
int i = 0;
int j = a.length-1;
//if(arr[i] > key)return -1;
if(a[j] < x)return a.length;
while(i<j)
{
int mid = (i+j)/2;
if(a[mid] == x)
{
j = mid;
}
else if(a[mid] < x)
{
i = mid+1;
}
else
j = mid-1;
}
return i;
}
int upper_bound(int [] arr , int key)
{
int i = 0;
int j = arr.length-1;
if(arr[j] <= key)return j+1;
while(i<j)
{
int mid = (i+j)/2;
if(arr[mid] <= key)
{
i = mid+1;
}
else
j = mid;
}
return i;
}
static void reverseArray(int arr[], int start,
int end)
{
while (start < end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 307a1c1333292a473cb18ac6d1773213 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
import static java.lang.System.out;
import static java.lang.System.err;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static FastReader sc;
static long mod=((long)1e9)+7;
// static FastWriter out;
public static void main(String hi[]){
initializeIO();
long startTimeProg=System.currentTimeMillis();
long endTimeProg=10000;
sc=new FastReader();
int t=sc.nextInt();
// int t=1;
// boolean[] seave=sieveOfEratosthenes((int)(1e7));
// int[] seave2=sieveOfEratosthenesInt((int)(1e4));
List<Long> li=new ArrayList<>();
for(long i=0;i<15;i++){
li.add(fact(i));
}
Collections.sort(li,Collections.reverseOrder());
long[] arr=new long[li.size()];
for(int i=0;i<li.size();i++){
arr[i]=li.get(i);
}
// debug(li.size());
while(t--!=0){
long sum=sc.nextLong();
if(isPowerOfTwo(sum)){
print(1);
}else{
min=Long.MAX_VALUE;
// dp=new ArrayList<>();
// for(int i=0;i<56;i++){
// dp.add(new HashMap<>());
// }
find(arr,0,0,sum,0);
print(min==Integer.MAX_VALUE?-1:min);
}
}
// System.out.println(String.format("%.9f", max));
endTimeProg=System.currentTimeMillis();
debug("[finished : "+(endTimeProg-startTimeProg)+".ms ]");
}
static long min=Long.MAX_VALUE;
public static void find(long[] arr, long currSum, int index, long sum,int e) {
int n=arr.length;
int i=index;
if(index>=n)return;
if(currSum<=sum){
long val=sum-currSum;
int c=0;
for(int j=0;(val>>j)>0;j++){
c+=(val>>j)&1;
}
min=min(c+e,min);
}else if(currSum>sum)return;
long take=Long.MAX_VALUE;
find(arr,currSum+arr[i],index+1,sum,e+1);
find(arr,currSum,index+1,sum,e);
// return min(take,dont);
}
private static String solve(long[] arr,int n){
// long[] sorted=arr.clone();
sortReverse(arr);
// debug(arr);
// int l=0,r=n-1;
long[] pre=new long[n+1];
long[] suff=new long[n+1];
pre[0]=arr[0];
for(int i=1;i<n;i++){
pre[i]+=pre[i-1]+arr[i];
}
suff[n-1]=arr[n-1];
for(int i=n-2;i>=0;i--){
suff[i]+=suff[i+1]+arr[i];
}
int l=0,r=n-2;
long sumr=0,sumb=0;
while(l<r){
// debug(l+" "+r);
if(pre[l]>suff[r])return "yes";
l++;
r--;
}
return "no";
}
private static boolean isSorted(List<Integer> li){
int n=li.size();
if(n<=1)return true;
for(int i=0;i<n-1;i++){
if(li.get(i)>li.get(i+1))return false;
}
return true;
}
static boolean isPowerOfTwo(long x)
{
return x != 0 && ((x & (x - 1)) == 0);
}
private static boolean ispallindromeList(List<Integer> res){
int l=0,r=res.size()-1;
while(l<r){
if(res.get(l)!=res.get(r))return false;
l++;
r--;
}
return true;
}
private static class Pair{
int first=0;
int sec=0;
int[] arr;
Map<Integer,Integer> map;
Pair(int first,int sec){
this.first=first;
this.sec=sec;
}
Pair(int[] arr){
this.map=new HashMap<>();
for(int x:arr) this.map.put(x,map.getOrDefault(x,0)+1);
this.arr=arr;
}
}
private static int sizeOfSubstring(int st,int e){
int s=e-st+1;
return (s*(s+1))/2;
}
private static List<Long> factors(long n){
List<Long> res=new ArrayList<>();
// res.add(n);
for (long i=1; i*i<=(n); i++){
if (n%i==0){
res.add(i);
if (n/i != i){
res.add(n/i);
}
}
}
return res;
}
private static long fact(long n){
if(n<=2)return n;
return n*fact(n-1);
}
private static long ncr(long n,long r){
return fact(n)/(fact(r)*fact(n-r));
}
private static int lessThen(long[] nums,long val){
int i=0,l=0,r=nums.length-1;
while(l<=r){
int mid=l+((r-l)/2);
if(nums[mid]<=val){
i=mid;
l=mid+1;
}else{
r=mid-1;
}
}
return i;
}
private static int lessThen(List<Long> nums,long val){
int i=0,l=0,r=nums.size()-1;
while(l<=r){
int mid=l+((r-l)/2);
if(nums.get(mid)<=val){
i=mid;
l=mid+1;
}else{
r=mid-1;
}
}
return i;
}
private static int greaterThen(List<Long> nums,long val){
int i=0,l=0,r=nums.size()-1;
while(l<=r){
int mid=l+((r-l)/2);
if(nums.get(mid)>=val){
i=mid;
r=mid-1;
}else{
l=mid+1;
}
}
return i;
}
private static int greaterThen(long[] nums,long val){
int i=nums.length-1,l=0,r=nums.length-1;
while(l<=r){
int mid=l+((r-l)/2);
if(nums[mid]>=val){
i=mid;
r=mid-1;
}else{
l=mid+1;
}
}
return i;
}
private static long sumOfAp(long a,long n,long d){
long val=(n*( 2*a+((n-1)*d)));
return val/2;
}
//geometrics
private static double areaOftriangle(double x1,double y1,double x2,double y2,double x3,double y3){
double[] mid_point=midOfaLine(x1,y1,x2,y2);
// debug(Arrays.toString(mid_point)+" "+x1+" "+y1+" "+x2+" "+y2+" "+x3+" "+" "+y3);
double height=distanceBetweenPoints(mid_point[0],mid_point[1],x3,y3);
double wight=distanceBetweenPoints(x1,y1,x2,y2);
// debug(height+" "+wight);
return (height*wight)/2;
}
private static double distanceBetweenPoints(double x1,double y1,double x2,double y2){
double x=x2-x1;
double y=y2-y1;
return sqrt(Math.pow(x,2)+Math.pow(y,2));
}
private static double[] midOfaLine(double x1,double y1,double x2,double y2){
double[] mid=new double[2];
mid[0]=(x1+x2)/2;
mid[1]=(y1+y2)/2;
return mid;
}
private static long sumOfN(long n){
return (n*(n+1))/2;
}
private static long power(long x,long y,long p){
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0){
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
/* Function to calculate x raised to the power y in O(logn)*/
static long power(long x, long y){
long temp;
if( y == 0)
return 1l;
temp = power(x, y / 2);
if (y % 2 == 0)
return (temp*temp);
else
return (x*temp*temp);
}
private static StringBuilder reverseString(String s){
StringBuilder sb=new StringBuilder(s);
int l=0,r=sb.length()-1;
while(l<=r){
char ch=sb.charAt(l);
sb.setCharAt(l,sb.charAt(r));
sb.setCharAt(r,ch);
l++;
r--;
}
return sb;
}
private static void swap(long arr[],int i,int j){
long t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
private static void swap(List<Integer> li,int i,int j){
int t=li.get(i);
li.set(i,li.get(j));
li.set(j,t);
}
private static void swap(int arr[],int i,int j){
int t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
private static void swap(double arr[],int i,int j){
double t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
private static void swap(float arr[],int i,int j){
float t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static long lcm(long a, long b){
return (a / gcd(a, b)) * b;
}
private static String decimalToString(int x){
return Integer.toBinaryString(x);
}
private static boolean isPallindrome(String s){
int l=0,r=s.length()-1;
while(l<r){
if(s.charAt(l)!=s.charAt(r))return false;
l++;
r--;
}
return true;
}
private static StringBuilder removeLeadingZero(StringBuilder sb){
int i=0;
while(i<sb.length()&&sb.charAt(i)=='0')i++;
// debug("remove "+i);
if(i==sb.length())return new StringBuilder();
return new StringBuilder(sb.substring(i,sb.length()));
}
private static StringBuilder removeEndingZero(StringBuilder sb){
int i=sb.length()-1;
while(i>=0&&sb.charAt(i)=='0')i--;
// debug("remove "+i);
if(i<0)return new StringBuilder();
return new StringBuilder(sb.substring(0,i+1));
}
private static int stringToDecimal(String binaryString){
// debug(decimalToString(n<<1));
return Integer.parseInt(binaryString,2);
}
private static int stringToInt(String s){
return Integer.parseInt(s);
}
private static String toString(int val){
return String.valueOf(val);
}
private static void debug(int[][] arr){
for(int i=0;i<arr.length;i++){
err.println(Arrays.toString(arr[i]));
}
}
private static void debug(long[][] arr){
for(int i=0;i<arr.length;i++){
err.println(Arrays.toString(arr[i]));
}
}
private static void debug(List<int[]> arr){
for(int[] a:arr){
err.println(Arrays.toString(a));
}
}
private static void debug(float[][] arr){
for(int i=0;i<arr.length;i++){
err.println(Arrays.toString(arr[i]));
}
}
private static void debug(double[][] arr){
for(int i=0;i<arr.length;i++){
err.println(Arrays.toString(arr[i]));
}
}
private static void debug(boolean[][] arr){
for(int i=0;i<arr.length;i++){
err.println(Arrays.toString(arr[i]));
}
}
private static void print(String s){
out.println(s);
}
private static void debug(String s){
err.println(s);
}
private static int charToIntS(char c){
return ((((int)(c-'0'))%48));
}
private static void print(double s){
out.println(s);
}
private static void print(float s){
out.println(s);
}
private static void print(long s){
out.println(s);
}
private static void print(int s){
out.println(s);
}
private static void debug(double s){
err.println(s);
}
private static void debug(float s){
err.println(s);
}
private static void debug(long s){
err.println(s);
}
private static void debug(int s){
err.println(s);
}
private static boolean isPrime(int n){
// Check if number is less than
// equal to 1
if (n <= 1)
return false;
// Check if number is 2
else if (n == 2)
return true;
// Check if n is a multiple of 2
else if (n % 2 == 0)
return false;
// If not, then just check the odds
for (int i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
private static List<List<Integer>> readUndirectedGraph(int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<n;i++){
int x=sc.nextInt();
int y=sc.nextInt();
graph.get(x).add(y);
graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readUndirectedGraph(int[][] intervals,int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<intervals.length;i++){
int x=intervals[i][0];
int y=intervals[i][1];
graph.get(x).add(y);
graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readDirectedGraph(int[][] intervals,int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<intervals.length;i++){
int x=intervals[i][0];
int y=intervals[i][1];
graph.get(x).add(y);
// graph.get(y).add(x);
}
return graph;
}
private static List<List<Integer>> readDirectedGraph(int n){
List<List<Integer>> graph=new ArrayList<>();
for(int i=0;i<=n;i++){
graph.add(new ArrayList<>());
}
for(int i=0;i<n;i++){
int x=sc.nextInt();
int y=sc.nextInt();
graph.get(x).add(y);
// graph.get(y).add(x);
}
return graph;
}
static String[] readStringArray(int n){
String[] arr=new String[n];
for(int i=0;i<n;i++){
arr[i]=sc.next();
}
return arr;
}
private static Map<Character,Integer> freq(String s){
Map<Character,Integer> map=new HashMap<>();
for(char c:s.toCharArray()){
map.put(c,map.getOrDefault(c,0)+1);
}
return map;
}
private static Map<Integer,Integer> freq(int[] arr){
Map<Integer,Integer> map=new HashMap<>();
for(int x:arr){
map.put(x,map.getOrDefault(x,0)+1);
}
return map;
}
static boolean[] sieveOfEratosthenes(long n){
boolean prime[] = new boolean[(int)n + 1];
for (int i = 2; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true){
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
return prime;
}
static int[] sieveOfEratosthenesInt(long n){
boolean prime[] = new boolean[(int)n + 1];
Set<Integer> li=new HashSet<>();
for (int i = 1; i <= n; i++){
prime[i] = true;
li.add(i);
}
for (int p = 2; p * p <= n; p++)
{
if (prime[p] == true){
for (int i = p * p; i <= n; i += p){
li.remove(i);
prime[i] = false;
}
}
}
int[] arr=new int[li.size()+1];
int i=0;
for(int x:li){
arr[i++]=x;
}
return arr;
}
public static long Kadens(List<Long> prices) {
long sofar=0;
long max_v=0;
for(int i=0;i<prices.size();i++){
sofar+=prices.get(i);
if (sofar<0) {
sofar=0;
}
max_v=Math.max(max_v,sofar);
}
return max_v;
}
public static int Kadens(int[] prices) {
int sofar=0;
int max_v=0;
for(int i=0;i<prices.length;i++){
sofar+=prices[i];
if (sofar<0) {
sofar=0;
}
max_v=Math.max(max_v,sofar);
}
return max_v;
}
static boolean isMemberAC(int a, int d, int x){
// If difference is 0, then x must
// be same as a.
if (d == 0)
return (x == a);
// Else difference between x and a
// must be divisible by d.
return ((x - a) % d == 0 && (x - a) / d >= 0);
}
private static void sort(int[] arr){
int n=arr.length;
List<Integer> li=new ArrayList<>();
for(int x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sortReverse(int[] arr){
int n=arr.length;
List<Integer> li=new ArrayList<>();
for(int x:arr){
li.add(x);
}
Collections.sort(li,Collections.reverseOrder());
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sort(double[] arr){
int n=arr.length;
List<Double> li=new ArrayList<>();
for(double x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sortReverse(double[] arr){
int n=arr.length;
List<Double> li=new ArrayList<>();
for(double x:arr){
li.add(x);
}
Collections.sort(li,Collections.reverseOrder());
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sortReverse(long[] arr){
int n=arr.length;
List<Long> li=new ArrayList<>();
for(long x:arr){
li.add(x);
}
Collections.sort(li,Collections.reverseOrder());
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static void sort(long[] arr){
int n=arr.length;
List<Long> li=new ArrayList<>();
for(long x:arr){
li.add(x);
}
Collections.sort(li);
for (int i=0;i<n;i++) {
arr[i]=li.get(i);
}
}
private static long sum(int[] arr){
long sum=0;
for(int x:arr){
sum+=x;
}
return sum;
}
private static long evenSumFibo(long n){
long l1=0,l2=2;
long sum=0;
while (l2<n) {
long l3=(4*l2)+l1;
sum+=l2;
if(l3>n)break;
l1=l2;
l2=l3;
}
return sum;
}
private static void initializeIO(){
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
System.setErr(new PrintStream(new FileOutputStream("error.txt")));
} catch (Exception e) {
// System.err.println(e.getMessage());
}
}
private static int maxOfArray(int[] arr){
int max=Integer.MIN_VALUE;
for(int x:arr){
max=Math.max(max,x);
}
return max;
}
private static long maxOfArray(long[] arr){
long max=Long.MIN_VALUE;
for(long x:arr){
max=Math.max(max,x);
}
return max;
}
private static int[][] readIntIntervals(int n,int m){
int[][] arr=new int[n][m];
for(int j=0;j<n;j++){
for(int i=0;i<m;i++){
arr[j][i]=sc.nextInt();
}
}
return arr;
}
private static long gcd(long a,long b){
if(b==0)return a;
return gcd(b,a%b);
}
private static int gcd(int a,int b){
if(b==0)return a;
return gcd(b,a%b);
}
private static int[] readIntArray(int n){
int[] arr=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
return arr;
}
private static double[] readDoubleArray(int n){
double[] arr=new double[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextDouble();
}
return arr;
}
private static long[] readLongArray(int n){
long[] arr=new long[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextLong();
}
return arr;
}
private static void print(int[] arr){
out.println(Arrays.toString(arr));
}
private static void print(long[] arr){
out.println(Arrays.toString(arr));
}
private static void print(String[] arr){
out.println(Arrays.toString(arr));
}
private static void print(double[] arr){
out.println(Arrays.toString(arr));
}
private static void debug(String[] arr){
err.println(Arrays.toString(arr));
}
private static void debug(Boolean[][] arr){
for(int i=0;i<arr.length;i++)err.println(Arrays.toString(arr[i]));
}
private static void debug(int[] arr){
err.println(Arrays.toString(arr));
}
private static void debug(long[] arr){
err.println(Arrays.toString(arr));
}
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while(st==null || !st.hasMoreTokens()){
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str="";
try {
str=br.readLine().trim();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
static class FastWriter {
private final BufferedWriter bw;
public FastWriter() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
static class Dsu {
int[] parent, size;
Dsu(int n) {
parent = new int[n + 1];
size = new int[n + 1];
for (int i = 0; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
}
private int findParent(int u) {
if (parent[u] == u) return u;
return parent[u] = findParent(parent[u]);
}
private boolean union(int u, int v) {
// System.out.println("uf "+u+" "+v);
int pu = findParent(u);
// System.out.println("uf2 "+pu+" "+v);
int pv = findParent(v);
// System.out.println("uf3 " + u + " " + pv);
if (pu == pv) return false;
if (size[pu] <= size[pv]) {
parent[pu] = pv;
size[pv] += size[pu];
} else {
parent[pv] = pu;
size[pu] += size[pv];
}
return true;
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 4e4d410aade30e54311dd65fef24d4df | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
Just have Patience + 1...
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = sc.nextInt();
for (int t = 1; t <= test; t++) {
solve();
}
out.close();
}
private static void solve() {
long n = sc.nextLong();
List<Long> factorials = new ArrayList<>();
factorials.add(1L);
long currVal = 1, factor = 2;
while (currVal * factor <= n) {
currVal *= factor;
factor++;
factorials.add(currVal);
}
int minPowerfulValuesUsed = 100, allSet = 1 << factorials.size();
for (int mask = 0; mask < allSet; mask++) {
long sum = 0;
int setBits = 0;
for (int bit = 0; bit < 15; bit++) {
if ((mask & (1 << bit)) >= 1) {
sum += factorials.get(bit);
setBits++;
}
}
long remaining = n - sum;
if (remaining < 0) {
continue;
}
minPowerfulValuesUsed = Math.min(minPowerfulValuesUsed, Long.bitCount(remaining) + setBits);
}
out.println(minPowerfulValuesUsed == 100 ? -1 : minPowerfulValuesUsed);
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | c547755e0983c0ef8ab3b17034ed23be | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
Just have Patience + 1...
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = sc.nextInt();
for (int t = 1; t <= test; t++) {
solve();
}
out.close();
}
private static void solve() {
long n = sc.nextLong();
List<Long> factorials = new ArrayList<>();
factorials.add(1L);
long currVal = 1, factor = 2;
while (currVal * factor <= n) {
currVal *= factor;
factor++;
factorials.add(currVal);
}
int minPowerfulValuesUsed = 100, allSet = 1 << factorials.size();
for (int mask = 0; mask < allSet; mask++) {
long sum = 0;
int setBits = 0;
for (int bit = 0; bit < 15; bit++) {
if ((mask & (1 << bit)) >= 1) {
sum += factorials.get(bit);
setBits++;
}
}
long remaining = n - sum;
if (remaining < 0) {
continue;
}
minPowerfulValuesUsed = Math.min(minPowerfulValuesUsed, Long.bitCount(remaining) + setBits);
}
out.println(minPowerfulValuesUsed);
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | b5900b2ac021e3a2c3aad2c57eb76c89 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main {
static MyScanner sc = new MyScanner();
static PrintWriter pw = new PrintWriter(System.out);
static int min = 1000;
public static void main(String[] args) throws Exception {
int fact = 2;
ArrayList<Long> al = new ArrayList<>();
al.add((long)1);
while(al.get(al.size()-1)*fact<=(long)(1e12)) {
al.add(al.get(al.size()-1)*fact);
fact++;
}
// for(int i = 0; i<al.size(); i++) {
// System.out.println(al.get(i));
// }
int t = sc.nextInt();
while(t-->0) {
long n = sc.nextLong();
int min = Integer.MAX_VALUE;
for(int i = 0; i<(1<<al.size()); i++) {
long sum = 0;
for(int j =0; j<31; j++) {
if((i&(1<<j))!=0) {
sum += al.get(j);
}
}
if(sum<=n) {
int rem = Long.bitCount((long)(n-sum));
rem += Long.bitCount((long)i);
min = Math.min(min, rem);
}
}
pw.println(min);
}
pw.close();
}
static void ruffleSort(int a[]) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < n; i++) {
int oi = r.nextInt(n);
int temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long a[]) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < n; i++) {
int oi = r.nextInt(n);
long temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | a7b284b9773e085b88a3594aa2776620 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.*;
public class Solution {
public static void main(String[] args) {
int t;
Scanner in= new Scanner(System.in);
t = in.nextInt();
while(t-- > 0) {
long n= in.nextLong();
HashMap<Long,Integer>map=new HashMap<>();
long[]fac=new long[15];fac[0]=1;
for(int i=1;i<15;i++) {
fac[i]=fac[i-1]*i;
}
int o=0;
for(int i=0;i<(1<<15);i++) {
long total=0;int count=0;
for(int j=0;j<15;j++) {
if(((1<<j)&i)>0) {
total+=fac[j];count++;
}
}
if(map.containsKey(total)) {
map.put(total, Math.min(map.get(total), count));
}
else {
map.put(total, count);
}
}
int v=0;
long ans=Integer.MAX_VALUE;
for(long key:map.keySet()) {
long l=n-key;
if(l<0) {continue;}
int count=map.get(key);
while(l>0) {
count+=l%2;l/=2;
}
ans=Math.min(ans, count);
}
System.out.println(ans);
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | e45b3abdd8a5fd00403e4a3651533765 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes |
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
public class k
{ //public static int mod=1000000007;
public static long printDivisors(long n, int k)
{
// Note that this loop runs till square root
long x=(long) Math.sqrt(n);
// int p=0;
long sum=0;
for (long i=1; i<=x; i++)
{
if (n%i == 0)
{
// If divisors are equal, print only one
if (n/i == i)
sum=sum+(long)(i);
else // Otherwise print both
sum=sum+(long)(i)+(long)(n/i);
}
if(sum>k)return -1;
}
return sum;
}
public static ArrayList<Long> Factors(long n)
{
ArrayList<Long> arr=new ArrayList<Long>();
int k=0;
while (n%2==0)
{
k++;
n /=2;
arr.add((long)2);
}
int p=(int) Math.sqrt(n);
for (int i = 3; i <=p; i+= 2)
{ if(n==1)break;
while (n%i == 0)
{
k++;
arr.add((long)i);
n /= i;
}
}
if (n > 2)
{
arr.add(n);
}
return arr;
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static long gcd(long x, long p)
{
if (x == 0)
return p;
return gcd(p%x, x);
}
// method to return LCM of two numbers
static long lcm(long a, long b)
{
return (a / gcd(a, b)) * b;
}
public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm)
{
// Create a list from elements of HashMap
List<Map.Entry<Integer, Integer> > list =
new LinkedList<Map.Entry<Integer, Integer> >(hm.entrySet());
// Sort the list
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() {
public int compare(Map.Entry<Integer, Integer> o1,
Map.Entry<Integer, Integer> o2)
{
return (o1.getValue()).compareTo(o2.getValue());
}
});
// put data from sorted list to hashmap
HashMap<Integer, Integer> temp = new LinkedHashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
static int sieve = 1000000 ;
static boolean[] prime = new boolean[sieve + 1] ;
static ArrayList<Integer> pr=new ArrayList<Integer>();
public static void sieveOfEratosthenes()
{
// FALSE == prime and 1 // TRUE == COMPOSITE
// time complexity = 0(NlogLogN)== o(N)
// gives prime nos bw 1 to N // size - 1e7(at max)
for(int i = 4; i<= sieve ; i++)
{
prime[i] = true ; i++ ;
}
for(int p = 3; p*p <= sieve; p++)
{
if(prime[p] == false)
{
pr.add(p);
for(int i = p*p; i <= sieve; i += p)
prime[i] = true;
}
p++ ;
}
}
public static void arrInpInt(int [] arr, int n) throws IOException
{
Reader reader = new Reader();
for(int i=0;i<n;i++)
{
arr[i]=reader.nextInt();
}
}
public static void arrInpLong(long [] arr, int n) throws IOException
{
Reader reader = new Reader();
for(int i=0;i<n;i++)
{
arr[i]=reader.nextLong();
}
}
public static void printArr(int[] arr)
{
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static int[] decSort(int[] arr)
{
int[] arr1 = Arrays.stream(arr).boxed().sorted(Collections.reverseOrder()).mapToInt(Integer::intValue).toArray();
return arr1;
}
//if present - return the first occurrence of the no
//not present- return the index of next greater value
//if greater than all the values return N(taking high=N-1)
//if smaller than all the values return 0(taking low =0)
static int lower_bound(long arr[], int low,int high, long X)
{
if (low > high) {
return low;
}
int mid = low + (high - low) / 2;
if (arr[mid] >= X) {
return lower_bound(arr, low,
mid - 1, X);
}
return lower_bound(arr, mid + 1,
high, X);
}
//if present - return the index of next greater value
//not present- return the index of next greater value
//if greater than all the values return N(taking high=N-1)
//if smaller than all the values return 0(taking low =0)\
static int upper_bound(long arr[], int low, int high, long X)
{
if (low > high)
return low;
int mid = low + (high - low) / 2;
if (arr[mid] <= X) {
return upper_bound(arr, mid + 1,
high, X);
}
return upper_bound(arr, low,
mid - 1, X);
}
public static class Pair {// comparator with class
int x;
int y;
public Pair(int x, int y)
{
this.x = x;
this.y = y;
}
}
public static void sortbyColumn(int arr[][], int col) // send 2d array and col no
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else if (entry1[col] < entry2[col])
return -1;
else return 0;
}
});
}
public static void sortbyColumn1(int arr[][], int col) // send 2d array and col no
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else if (entry1[col] < entry2[col])
return -1;
else if(entry1[col] == entry2[col])
{
if(entry1[col-1]>entry2[col-1])
return -1;
else if(entry1[col-1]<entry2[col-1])
return 1;
else return 0;
}
else return 0;
}
});
}
public static void print2D(int mat[][])
{
// Loop through all rows
for (int i = 0; i < mat.length; i++)
{ // Loop through all elements of current row
{
for (int j = 0; j < mat[i].length; j++)
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
public static int biggestFactor(int num) {
int result = 1;
for(int i=2; i*i <=num; i++){
if(num%i==0){
result = num/i;
break;
}
}
return result;
}
public static int knapsack(int[] weights,int[] price, int totW)
{
int[] dp1=new int[totW+1];
int[] dp2=new int[totW+1];
int N=totW;
int ans=0;
for(int i=0;i<price.length;i++)
{
for(int j=0;j<=N;j++)
{
if(weights[i]>j)
{
if(i%2==0)
{
dp1[j]=dp2[j];
}
else
{
dp2[j]=dp1[j];
}
}
else
{
if(i%2==0)
{
dp1[j]=Math.max(dp2[j],dp2[j-weights[i]]+price[i]);
}
else
{
dp2[j]=Math.max(dp1[j], dp1[j-weights[i]]+price[i]);
}
}
}
if(i%2==0)ans=dp1[N];
else ans=dp2[N];
}
return ans;
}
public static class p
{
int no;
int h;
public p(int no, long h)
{
this.no=no;
this.h=(int) h;
}
}
static class com implements Comparator<p>{
public int compare(p s1, p s2) {
if (s1.h > s2.h)
return -1;
else if (s1.h < s2.h)
return 1;
else if(s1.h==s2.h)
{
if(s1.no>s2.no)return -1;
else return 1;
}
return 0;
}
}
static long hcf(long a,long b)
{
while (b > 0)
{
long temp = b;
b = a % b;
a = temp;
}
return a;
}
static int lower_bound_arr(ArrayList<Integer> arr, int low,
int high, int X)
{
if (low > high) {
return low;
}
int mid = low + (high - low) / 2;
if (arr.get(mid) >= X) {
return lower_bound_arr(arr, low,
mid - 1, X);
}
return lower_bound_arr(arr, mid + 1,
high, X);
}
public static int func2(int m,int[] arr,int k,int[] arr1)
{
for(int i=0;i<arr.length;i++)
{
int p=arr[i];
int q=arr[i]+m;
int in=(q<=arr.length?arr1[q]:arr.length)-arr1[p-1];
if((in)-(arr.length-in)>=k)return arr[i];
}
return 0;
}
public static boolean func(int m,int[] arr,int k,int[] arr1)
{
for(int i=0;i<arr.length;i++)
{
int p=arr[i];
int q=arr[i]+m;
int in=(q<=arr.length?arr1[q]:arr.length)-arr1[p-1];
if((in)-(arr.length-in)>=k)return true;
}
return false;
}
public static int binarySearch(int min, int max, int[] arr,int k,int[] arr1)
{
int l = min, r = max;
while (l <= r) {
int m = l + (r - l) / 2;
boolean x11=func(m,arr,k,arr1);
boolean x1=func(m-1,arr,k,arr1);
if(x11 && !x1)return m;
//Check if x is present at mid
// if (arr[m] == x)
// return m;
// If x greater, ignore left half
if (!x1 && !x11)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
return max;
}
static long isP(long x)
{
if (x >= 0) {
// Find floating point value of
// square root of x.
long sr = (long)Math.sqrt(x);
// if product of square root
// is equal, then
// return T/F
long k=sr*sr;
if(k == x)return sr;
}
return -1;
}
// public static long func(Integer[] arr, int k)
// {
//
// }
// public static HashMap<String,Integer> map1=new HashMap<String,Integer>();
// public static int function1(int[][] arr1,Integer[] arr, int start, int end)
// {
//// System.out.println("1");
//
// int p=0;
// int n=0;
// p=arr1[end][0]-arr1[start-1][0];
// n=arr1[end][1]-arr1[start-1][1];
//// return Math.abs(n-p);
// if(n==p)return 0;
// if(map1.containsKey(start+" "+end))return map1.get(start+" "+end);
// else
// {
// int min=Integer.MAX_VALUE;
// int n1=0;
// int p1=0;
// for(int i=end-1;i>=start-1;i--)
// {
//// System.out.println("pp");
//// int P=p-(arr[i]==1?1:0)-p1+n1;
//// int N=n-(arr[i]==-1?1:0)-n1+p1;
// int P=(arr[i]==1?1:0)-p1+n1;
// int N=(arr[i]==-1?1:0)-n1+p1;
// if(arr[i]==-1)n1++;
// else p1++;
//
// p=arr1[end][0]-arr1[i+1][0];
// n=arr1[end][1]-arr1[i+1][1];
//
//// min=Math.min(Math.abs(P-N), min);
//// map1.put((i+1)+" "+end,min+1);
// }
//
//
//
// return min;
// }
// }
public static long pwmd(long a, long n,long mod) {
if (n == 0)
return 1;
long pt = pwmd(a, n / 2,mod);
pt *= pt;
pt %= mod;
if ((n & 1) > 0) {
pt *= a;
pt %= mod;
}
return pt;
}
static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
@Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
return res != 0 ? res : 1; // Special fix to preserve items with equal values
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
// HashSet<Long> map=n
public static HashMap<Long,Integer> set=new HashMap<Long,Integer>();
public static void sum(long[] arr, long sum,int ind,int count)
{
// System.out.println(1);
if(ind>=arr.length)return;
set.put(sum,set.containsKey(sum)?Math.min(set.get(sum), count) :count);
set.put(sum+arr[ind], set.containsKey(sum+arr[ind])?Math.min(set.get(sum+arr[ind]), count+1) :count+1);
// System.out.println(sum + " "+ (sum+arr[ind]));
sum(arr,sum,ind+1,count);
sum(arr,sum+arr[ind],ind+1,count+1);
}
public static void main(String args[]) throws NumberFormatException, IOException ,java.lang.Exception
{
Reader reader = new Reader();
long mod= 998244353;
long temp[] =new long[16];
long mul=2l;
for(int i=3;i<18;i++)
{
temp[i-3]=mul*(long)(i);
mul=mul*(long)(i);
}
sum(temp,0,0,0);
// System.out.println(set);
// System.out.println(set.get(4l));
// System.out.println(set.containsKey(key));
// System.out.println(Arrays.toString(temp));
// System.out.println(set);
// System.out.println(set.size());
// subsetSums(temp,0,53,0,0);
// Arrays.sort(temp);
// System.out.println(Arrays.toString(temp));
// for(int i=0;i<54;i++)
// {
// long sum=0;
// long k=0;
// for(int j=i;j<54;j++)
// {
// sum=sum+temp[j];
// k++;
// if(map.containsKey(sum))
// {
// if(map.get(sum)>k)
// {
// map.put(sum, k);
// }
// }
// else map.put(sum, k);
// }
//
// }
//// power();
// long[] pow2 =new long[64];
// pow2[0]=1l;
// for(int i=1;i<64;i++)
// {
//// pow2[i]=(int) Math.pow(2, i);
// pow2[i]=((long)(2)*pow2[i-1]);
//// System.out.println(pow2[i]);
// }
// sieveOfEratosthenes();
//Scanner reader=new Scanner(System.in);
// PrintWriter out = new PrintWriter(System.out);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
// int cases=Integer.parseInt(br.readLine());
// int cases=1;
int cases=reader.nextInt();
while (cases-->0){
long N=reader.nextLong();
//
// long M=reader.nextLong();
// long X=reader.nextLong();
// long Y=reader.nextLong();
// long H2=reader.nextLong();
// long D2=reader.nextLong();
//
// long C=reader.nextLong();
// long W=reader.nextLong();
// long A=reader.nextLong();
// int N=reader.nextInt();
// int M=reader.nextInt();
// int K=reader.nextInt();
// int P=reader.nextInt();
// int K=reader.nextInt();
// long M=reader.nextLong();
//
// long X=reader.nextLong();
// String p="";
// while(p.equals(""))p=br.readLine();
//////
// String[] first=br.readLine().split(" ");
// int N=Integer.parseInt(first[0]);
// int M=Integer.parseInt(first[1]);
// String[] first2=br.readLine().split(" ");
// String[] first3=br.readLine().split(" ");
// int M=Integer.parseInt(first1[1]);
// long K=Long.parseLong(first1[0]);
// long X=Long.parseLong(first1[1]);
// String s3=br.readLine();
// char[] s11=s2.toCharArray();
// char[] s12=new char[s11.length];
int max=Integer.MIN_VALUE;
// int max1=Integer.MIN_VALUE;
int min=Integer.MAX_VALUE;
// long min=Inteeg.MAX_VALUE;
// int min1=Integer.MAX_VALUE;
// int min2=Integer.MAX_VALUE;
// HashMap<Integer, Integer> map=new HashMap<Integer,Integer>();
// PriorityQueue<Integer> q = new PriorityQueue<Integer>(Collections.reverseOrder());
// PriorityQueue<Long> q = new PriorityQueue<Long>(Collections.reverseOrder());
// HashMap<Integer,TreeSet<Integer>> map=new HashMap<Integer,TreeSet<Integer>>();
// HashMap<Long,Long> map=new HashMap<Long,Long>();
// HashMap<String,String> map1=new HashMap<String,String>();
// TreeMap<Integer,Integer> map1=new TreeMap<Integer,Integer>();
// List<TreeMap<Integer,Integer>> map = new ArrayList<TreeMap<Integer,Integer>>();
// HashSet<Character> set =new HashSet<Character>();
// HashSet<String> set1 =new HashSet<String>();
// HashSet<Integer> map =new HashSet<Integer>();
// HashSet<Integer> set =new HashSet<Integer>();
// TreeSet<Integer> a =new TreeSet<Integer>();
//TreeSet<Long> b =new TreeSet<Long>();
// TreeSet<Integer> map=new TreeSet<Integer>();
// int[] arr=new int[(int)M];
// int[] arr=new int[N];
// int[] arr2=new int[64];
// int[] ev=new int[N];
// int[] od=new int[N];
//
// long[] arr=new long[N];
// int[] arr2=new int[32];// i00nt[] odd=new int[100001];
// int[] arr=new int[N];
// int[] arr2=new int[5];
// Integer[] arr=new Integer[N];
// Integer[] arr1=new Integer[N];
// long[] arr=new long[N];
// Long[] arr=new Long[N];
// int[][] arr=new int[N][2];
// int[][] arr=new int[N][2];
// ArrayList<Long> list=new ArrayList<Long>();
// ArrayList<String> l=new ArrayList<String>();
// ArrayList<String> even=new ArrayList<String>();
// ArrayList<Integer> odd=new ArrayList<Integer>();
// ArrayList<Long> bees=new ArrayList<Long>();
// boolean[]arr1=new boolean[N];
//
// rec(long n, long[] arr, long count )
// public static int rec(long n, long[] arr, long count ,int in)
int min1=Integer.MAX_VALUE;
for (Map.Entry<Long,Integer> entry : set.entrySet())
{
long p=entry.getKey();
if(p>N)
{continue;}
int c=entry.getValue();
int k=0;
long rem=N-p;
for(int i=0;i<64;i++)
{
if(((rem>>i)&1)==1)k++;
}
min1=Math.min(k+c, min1);
}
System.out.println(min1);
}
// output.flush();
}}
// output.flush();
// output.flush();
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 7abf73327cafa22f1cdb6d92ad596430 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | //package com.company;
import java.util.*;
import java.lang.*;
import java.io.*;
public class Rough_Work {
private static long[] pre;
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
pre = new long[12];
pre[0] = 6;
for (int i = 1; i < 12; i++) {
pre[i] = pre[i-1]*(i+3);
}
int t = sc.nextInt();
while (t-->0){
long n = sc.nextLong();
int cnt = count(n);
if (cnt == 1){
out.println(1);
continue;
}
out.println(find_cost(n,11));
}
sc.close();
out.close();
}
static int find_cost (long n, int i){
int cnt = count(n);
for (int j = i; j >= 0; j--) {
cnt = Math.min(cnt, 1+find_cost(n - pre[j],j-1));
}
return cnt;
}
static int count (long n) {
int ret = (int) (n&1);
for (int i = 0; i < 41; i++) {
n = n >> 1;
ret += (int) (n&1);
}
return ret;
}
static class FastReader {
final private int BUFFER_SIZE = 1 << 17;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[128]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
public int[] nextIntArray(int size) throws IOException {
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int size) throws IOException {
long[] arr = new long[size];
for (int i = 0; i < size; i++) {
arr[i] = nextLong();
}
return arr;
}
public Double[] nextDoubleArray(int size) throws IOException {
Double[] arr = new Double[size];
for (int i = 0; i < size; i++) {
arr[i] = nextDouble();
}
return arr;
}
public int[][] nextIntMatrix(int n, int m) throws IOException {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
public long[][] nextLongMatrix(int n, int m) throws IOException {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
public ArrayList<Integer> nextIntList(int size) throws IOException {
ArrayList<Integer> arrayList = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
arrayList.add(nextInt());
}
return arrayList;
}
public ArrayList<Long> nextLongList(int size) throws IOException {
ArrayList<Long> arrayList = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
arrayList.add(nextLong());
}
return arrayList;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 5aade39d7fb86b0a1c4d024c14f85dad | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Contest1646C
{
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() { // reads in the next string
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() { // reads in the next int
return Integer.parseInt(next());
}
public long nextLong() { // reads in the next long
return Long.parseLong(next());
}
public double nextDouble() { // reads in the next double
return Double.parseDouble(next());
}
}
static InputReader r = new InputReader(System.in);
static PrintWriter pw = new PrintWriter(System.out);
static long mod = 1000000007; static ArrayList<Long> facs,pows;
public static void main(String[] args)
{
int t = r.nextInt();
while (t > 0)
{
t--;
long n = r.nextLong();
pows = new ArrayList<Long>();
int next = 1;
facs = new ArrayList<Long>();
long[] facs = new long[14];
long fac = 1;
for (int i = 0; i < 14; i ++)
{
fac *= (i + 1);
facs[i] = fac;
}
HashMap<Long,Integer> map = new HashMap<Long,Integer>();
int[] num = new int[1 << 14];
for (int s = 0; s < (1 << 14); s ++)
{
long sum = 0;
int count = 0;
for (int i = 0; i < 14; i ++)
{
if ((s & (1 << i)) > 0)
{
sum += facs[i];
count ++;
}
}
num[s] = count;
map.put(sum, map.containsKey(sum) ? Math.min(map.get(sum), count) : count);
}
int ans = Integer.MAX_VALUE;
for (long x: map.keySet())
{
long m = n - x;
if (m < 0)
{
continue;
}
int y = map.get(x);
while (m > 0)
{
y += m%2;
m/=2;
}
ans = Math.min(ans, y);
}
pw.println(ans);
}
pw.close();
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 4a799945a90293ee0cfb0398f2e070ff | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes |
// import java.io.*;
// import java.util.*;
// public class Main{
// static class FastReader {
// BufferedReader br;
// StringTokenizer st;
// public FastReader()
// {
// br = new BufferedReader(
// new InputStreamReader(System.in));
// }
// String next()
// {
// while (st == null || !st.hasMoreElements()) {
// try {
// st = new StringTokenizer(br.readLine());
// }
// catch (IOException e) {
// e.printStackTrace();
// }
// }
// return st.nextToken();
// }
// int nextInt() { return Integer.parseInt(next()); }
// long nextLong() { return Long.parseLong(next()); }
// double nextDouble()
// {
// return Double.parseDouble(next());
// }
// String nextLine()
// {
// String str = "";
// try {
// str = br.readLine();
// }
// catch (IOException e) {
// e.printStackTrace();
// }
// return str;
// }
// }
// public static class Pair implements Comparable<Pair>
// {
// double cpu;
// int tu;
// int op;
// int cost;
// Pair(double cpu,int tu,int op,int cost)
// {
// this.cpu=cpu;
// this.tu=tu;
// this.op=op;
// this.cost=cost;
// }
// public int compareTo(Pair o)
// {
// return (int)(o.cpu-this.cpu);
// }
// }
// public static void main(String[] args) throws Exception {
// FastReader sc = new FastReader();
// int t=sc.nextInt();
// while(t-->0)
// {
// int n=sc.nextInt();
// int k=sc.nextInt();
// int[] val=new int[n];
// int[] coins=new int[n];
// for(int i=0;i<n;i++)
// {
// val[i]=sc.nextInt();
// }
// for(int i=0;i<n;i++)
// {
// coins[i]=sc.nextInt();
// }
// Pair cost[]=new Pair[n];
// for(int i=0;i<n;i++)
// {
// double sum=val[i]/(i+1)+1;
// int op=Math.log(10)/Math.sum;
// if(val[i]%(i+1)!=0)
// {
// op++;
// }
// int tu=val[i];
// double cpu=coins[i]/val[i];
// cost[i]=new Pair(cpu,tu,op,coins[i]);
// }
// Arrays.sort(cost);
// for( Pair i:cost)
// {
// System.out.print(i.cpu+","+i.op+"-"+i.cost+"**");
// }
// System.out.println();
// long ans=0;
// for(int i=0;i<n;i++)
// {
// long amt=cost[i].cost;
// if(cost[i].op<=k)
// {
// k-=cost[i].op;
// ans+=amt;
// System.out.print(cost[i].op+" ");
// }
// }
// System.out.println(ans);
// }
// }
// }
import java.io.*;
import java.util.*;
import javax.sound.midi.SysexMessage;
import javax.swing.text.AbstractDocument.LeafElement;
public class Main{
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static class Pair implements Comparable<Pair>
{
int i;
int j;
Pair(int i,int j)
{
this.i=i;
this.j=j;
}
public int compareTo(Pair o)
{
return this.i-o.i;
}
}
public static void main(String[] args) throws Exception
{
FastReader sc = new FastReader();
int t=sc.nextInt();
ArrayList<Long> al=new ArrayList<>();
ArrayList<Long> dp=new ArrayList<>();
long res=1;
for(long i=2;i<=30;i++)
{
al.add(res);
res*=i;
}
while(t-->0)
{
long n=sc.nextLong();
long ct=0;
res=n;
long p=(long)Math.pow(2,15);
for(int i=0;i<=p;i++)
{
long temp=0,temp_res=0;
for(int j=0;j<=20;j++)
{
int pow=1<<j;
if((pow&i)>0)
{
temp++;
temp_res +=al.get(j);
}
}
long cnt = 0;
long x = n-temp_res;
while(x>0)
{
if((x&1)>0)
{
cnt++;
}
x/=2;
}
if(temp_res<=n)
{
res = Math.min(res,temp+cnt);
}
}
System.out.println(res);
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 7ef50b733fb41307dd11d530853c2dae | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) {
factorials = new long[15];
factorials[0] = 1;
for (int i = 1; i < 15; i++) {
factorials[i] = factorials[i - 1] * i;
}
hs = new TreeMap<>();
HashMap<Long, Integer> tmp = new HashMap<>();
hs.put(0L, 0);
for (int i = 0; i < 15; i++) {
for (long j : hs.keySet()) {
tmp.put(j + factorials[i], hs.get(j) + 1);
}
hs.putAll(tmp);
tmp.clear();
}
while (N-- > 0) {
solve();
}
out.close();
}
public static void solve() {
long n = sc.nextLong();
int res = count1(n);
for (long i : hs.keySet()) {
if (n - i < 0) {
break;
}
res = Math.min(count1(n - i) + hs.get(i), res);
}
out.println(res);
}
private static int count1(long n) {
int res = 0;
while (n > 0) {
res += n & 1;
n >>= 1;
}
return res;
}
private static TreeMap<Long, Integer> hs;
private static long[] factorials;
private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
private static MyScanner sc = new MyScanner();
private static int N = sc.nextInt();
private final static int MOD = 1000000007;
@SuppressWarnings("unused")
private static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 0df192f37da2b0a38d41efe5265205d6 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import java.util.*;
import java.io.*;
import java.math.*;
/**
*
* @Har_Har_Mahadev
*/
/**
* Main , Solution , Remove Public
*/
public class C {
private static ArrayList<Long> set;
private static HashMap<Long, Integer> lis;
public static void process() throws IOException {
long n = sc.nextLong();
set = new ArrayList<Long>();
long ans = 1;
for(int i = 2; i<=n; i++) {
ans*=i;
if(ans <= n) {
set.add(ans);
continue;
}
break;
}
lis = new HashMap<Long, Integer>();
solve(0, 0, 0);
ans = 1;
while(ans <= n) {
lis.remove(ans);
ans*=2;
}
long max = Long.bitCount(n);
for(long e : lis.keySet()) {
int val = lis.get(e);
long res = n-e;
if(res < 0)continue;
val+=Long.bitCount(res);
max = min(max, val);
}
System.out.println(max);
}
private static void solve(int i, long j, int k) {
if(i>=set.size()) {
lis.put(j, min(lis.getOrDefault(j, Integer.MAX_VALUE), k));
return;
}
solve(i+1, j, k);
solve(i+1, j+set.get(i), k+1);
}
//=============================================================================
//--------------------------The End---------------------------------
//=============================================================================
private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353;
private static int N = 0;
private static void google(int tt) {
System.out.print("Case #" + (tt) + ": ");
}
static FastScanner sc;
static FastWriter out;
public static void main(String[] args) throws IOException {
boolean oj = true;
if (oj) {
sc = new FastScanner();
out = new FastWriter(System.out);
} else {
sc = new FastScanner("input.txt");
out = new FastWriter("output.txt");
}
long s = System.currentTimeMillis();
int t = 1;
t = sc.nextInt();
int TTT = 1;
while (t-- > 0) {
// google(TTT++);
process();
}
out.flush();
// tr(System.currentTimeMillis()-s+"ms");
}
private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private static void tr(Object... o) {
if (!oj)
System.err.println(Arrays.deepToString(o));
}
static class Pair implements Comparable<Pair> {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(this.x, o.x);
}
/*
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pair)) return false;
Pair key = (Pair) o;
return x == key.x && y == key.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
*/
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static int ceil(int x, int y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
static long sqrt(long z) {
long sqz = (long) Math.sqrt(z);
while (sqz * 1L * sqz < z) {
sqz++;
}
while (sqz * 1L * sqz > z) {
sqz--;
}
return sqz;
}
static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
public static long gcd(long a, long b) {
if (a > b)
a = (a + b) - (b = a);
if (a == 0L)
return b;
return gcd(b % a, a);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static int lower_bound(int[] arr, int x) {
int low = 0, high = arr.length - 1, mid = -1;
int ans = -1;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] > x) {
high = mid - 1;
} else {
ans = mid;
low = mid + 1;
}
}
return ans;
}
public static int upper_bound(int[] arr, int x) {
int low = 0, high = arr.length - 1, mid = -1;
int ans = arr.length;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x) {
ans = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return ans;
}
static void ruffleSort(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
Arrays.sort(a);
}
static void reverseArray(int[] a) {
int n = a.length;
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void reverseArray(long[] a) {
int n = a.length;
long arr[] = new long[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
//custom multiset (replace with HashMap if needed)
public static void push(TreeMap<Integer, Integer> map, int k, int v) {
//map[k] += v;
if (!map.containsKey(k))
map.put(k, v);
else
map.put(k, map.get(k) + v);
}
public static void pull(TreeMap<Integer, Integer> map, int k, int v) {
//assumes map[k] >= v
//map[k] -= v
int lol = map.get(k);
if (lol == v)
map.remove(k);
else
map.put(k, lol - v);
}
// compress Big value to Time Limit
public static int[] compress(int[] arr) {
ArrayList<Integer> ls = new ArrayList<Integer>();
for (int x : arr)
ls.add(x);
Collections.sort(ls);
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int boof = 1; //min value
for (int x : ls)
if (!map.containsKey(x))
map.put(x, boof++);
int[] brr = new int[arr.length];
for (int i = 0; i < arr.length; i++)
brr[i] = map.get(arr[i]);
return brr;
}
// Fast Writer
public static class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE)
innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000)
return 10;
if (l >= 100000000)
return 9;
if (l >= 10000000)
return 8;
if (l >= 1000000)
return 7;
if (l >= 100000)
return 6;
if (l >= 10000)
return 5;
if (l >= 1000)
return 4;
if (l >= 100)
return 3;
if (l >= 10)
return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L)
return 19;
if (l >= 100000000000000000L)
return 18;
if (l >= 10000000000000000L)
return 17;
if (l >= 1000000000000000L)
return 16;
if (l >= 100000000000000L)
return 15;
if (l >= 10000000000000L)
return 14;
if (l >= 1000000000000L)
return 13;
if (l >= 100000000000L)
return 12;
if (l >= 10000000000L)
return 11;
if (l >= 1000000000L)
return 10;
if (l >= 100000000L)
return 9;
if (l >= 10000000L)
return 8;
if (l >= 1000000L)
return 7;
if (l >= 100000L)
return 6;
if (l >= 10000L)
return 5;
if (l >= 1000L)
return 4;
if (l >= 100L)
return 3;
if (l >= 10L)
return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map)
write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
// Fast Inputs
static class FastScanner {
//I don't understand how this works lmao
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1)
return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] readArray(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] readArrayLong(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public int[][] readArrayMatrix(int N, int M, int Index) {
if (Index == 0) {
int[][] res = new int[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
res[i][j] = (int) nextLong();
}
return res;
}
int[][] res = new int[N][M];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++)
res[i][j] = (int) nextLong();
}
return res;
}
public long[][] readArrayMatrixLong(int N, int M, int Index) {
if (Index == 0) {
long[][] res = new long[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
res[i][j] = nextLong();
}
return res;
}
long[][] res = new long[N][M];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++)
res[i][j] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC)
c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-')
neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] readArrayDouble(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32)
c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32)
return true;
while (true) {
c = getChar();
if (c == NC)
return false;
else if (c > 32)
return true;
}
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 4730bae7527f8d37f8df88cb0cbe9fb5 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CFactorialsAndPowersOfTwo solver = new CFactorialsAndPowersOfTwo();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class CFactorialsAndPowersOfTwo {
long[] facs;
int[] dp;
public void solve(int testNumber, InputReader in, OutputWriter out) {
long n = in.nextLong();
if ((n & (n - 1)) == 0) {
out.println(1);
return;
}
long f = 1;
int x = 1;
facs = new long[20];
facs[0] = 1;
for (long i = 1; i <= 15; i++) {
f *= i;
facs[(int) i] = f;
}
dp = new int[1 << 16];
Arrays.fill(dp, -1);
// out.println(facs);
out.println(rec(0, n));
}
int rec(int mask, long val) {
if (dp[mask] != -1) return dp[mask];
int ans = Integer.bitCount(mask) + Long.bitCount(val);
for (int i = 0; i <= 15; i++) {
if (((1 << i) & mask) == 0 && val - facs[i] >= 0) {
ans = Math.min(ans, rec((1 << i) | mask, val - facs[i]));
}
}
return dp[mask] = ans;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 374b294be145ed32e6b83ee9e91bc009 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class cf {
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
long fac = 1;
int p = 2;
while (fac <= 1e12) {
arr[p - 2] = fac;
fac *= p;
p++;
}
gen(0, 0, 0);
// pw.println(hm);
int t = sc.nextInt();
while (t-- > 0) {
long s = sc.nextLong();
int min = Integer.MAX_VALUE;
for (long x : hm.keySet()) {
if (x <= s) {
// pw.println(x + " " + hm.get(x) + " " + Long.bitCount(s - x));
min = Math.min(min, hm.get(x) + Long.bitCount(s - x));
}
}
pw.println(min);
}
pw.close();
}
static HashMap<Long, Integer> hm = new HashMap<>();
static long[] arr = new long[14];
static void gen(int i, int c, long s) {
hm.put(s, Math.min(hm.getOrDefault(s, Integer.MAX_VALUE), c));
if (i == 14) {
return;
}
gen(i + 1, c + 1, s + arr[i]);
gen(i + 1, c, s);
}
public static class tuble implements Comparable<tuble> {
int x;
int y;
int z;
String w;
public tuble(int x, int y, int z, String w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
public String toString() {
return x + " " + y + " " + z;
}
public int compareTo(tuble other) {
if (this.x == other.x) {
if (this.y == other.y)
return this.z - other.z;
return this.y - other.y;
} else {
return this.x - other.x;
}
}
}
public static class pair implements Comparable<pair> {
int x;
int y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
if (o instanceof pair) {
pair p = (pair) o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Integer(x).hashCode() * 31 + new Integer(y).hashCode();
}
public int compareTo(pair other) {
if (this.x == other.x) {
return Long.compare(this.y, other.y);
}
return Long.compare(this.x, other.x);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | ba1e79b5294330f3c49bd10ab3810c99 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class C1646 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
ArrayList<Long> fact = new ArrayList<>();
long cur = 6;
for (int i = 4; cur <= (long) 1e12; i++) {
fact.add(cur);
cur *= i;
}
int t = sc.nextInt();
while (t-- > 0) {
long n = sc.nextLong();
int ans = (int) 1e9;
for (int i = 0; i < 1 << fact.size(); i++) {
long x = 0;
int cand = 0;
for (int j = 0; j < fact.size(); j++) {
if ((i & (1 << j)) != 0) {
x += fact.get(j);
cand++;
}
}
if (x > n)
continue;
x = n - x;
while (x > 0) {
cand += x & 1;
x >>= 1;
}
ans = Math.min(ans, cand);
}
pw.println(ans);
}
pw.close();
// int max = (int) 1e6 + 1;
// int[] dp = new int[max];
// for (int i = 1; i < max; i++) {
// dp[i] = (int) 1e9;
// for (long x : mynums) {
// if (i - x >= 0)
// dp[i] = Math.min(dp[i], 1 + dp[(int) (i - x)]);
// }
// if (dp[i] != solve1(i)) {
// System.out.println(i + " " + dp[i] + " " + solve1(i));
//// break;
// }
// }
pw.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader f) {
br = new BufferedReader(f);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(next());
}
return arr;
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | b96f86714a3be7a02a66967e7beb2141 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class C_Factorials_and_Powers_of_Two {
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
long[] getArr(int n) {
long[] res = new long[n];
for(int i = 0; i < n; i++){
res[i] = Long.parseLong(next());
}
return res;
}
}
public static void main(String[] args) {
FastScanner fs = new FastScanner();
Integer cases = fs.nextInt();
List<Long> list = new ArrayList<>();
long cur = 1l;
for(int i = 1; i < 15; i++){
cur *= (long)i;
list.add(cur);
}
// System.out.println(convert(7));
// System.out.println(convert(8));
// System.out.println(convert(9));
for(int i = 0; i < cases; i++){
Long num = fs.nextLong();
System.out.println(travel(num,list));
}
}
public static long travel(long a,List<Long> list){
long res = convert(a);
// System.out.println(res);
for(int i = 1; i < (1 <<list.size()); i++){
long total = 0l;
int index = 0;
int val = i;
int count = 0;
while(val > 0){
if(val % 2 == 1){
count += 1;
total += list.get(index);
}
index += 1;
val /= 2;
}
if(total <= a){
// System.out.println(count);
// System.out.println(a - total);
// System.out.println(total+" "+i);
count += convert(a - total);
// System.out.println(count);
// System.out.println();
res = Math.min(res,count);
}
}
return res;
}
public static long convert(long a){
long count = 0l;
while(a > 0){
if(a % 2 == 1){
count += 1;
}
a /= 2l;
}
return count;
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | e5979ab74ba9d4bae5397769a055a246 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.*;// hamare sath shri Raghunath, to kis baat ki chinta..........
import java.lang.*;// discipline is doing what needs to be done even if you don't want to do it.
import java.io.*;
public class a {
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
public static void main (String[] args) throws java.lang.Exception {
long fact[] = new long[14];
fact[0] = 1;
for(int i = 1; i < 14; i++){
fact[i] = (i+1)*fact[i-1];
}
int tc = sc.nextInt();
while(tc-->0){
long n = sc.nextLong();
int ans = Integer.MAX_VALUE;
for(int i = 0; i < (1 << 14); i++){
long sum = 0;
for(int j = 0; j < 14; j++){
if((i & (1<<j)) != 0){
sum += fact[j];
}
}
if(sum > n)
break;
int temp = cnt(i);
temp += cnt(n-sum);
ans = Math.min(ans,temp);
}
out.println(ans);
}
out.flush();
}
static int cnt(long n){
int cnt = 0;
while(n > 0){
if(n % 2 != 0)
cnt++;
n /= 2;
}
return cnt;
}
}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 529bd8a7a4557ba26e24053bebbb86d3 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
public class Main
{
static class Pair
{
long a,b;
public Pair(long a,long b)
{
this.a=a;
this.b=b;
}
// @Override
// public int compareTo(Pair p) {
// return Long.compare(l, p.l);
// }
}
static final int INF = 1 << 30;
static final long INFL = 1L << 60;
static final long NINF = INFL * -1;
static final long mod = (long) 1e9 + 7;
static final long mod2 = 998244353;
static DecimalFormat df = new DecimalFormat("0.00000000000000");
public static final double PI = 3.141592653589793d, eps = 1e-9;
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC
{
public static void solve(int testNumber, InputReader in, OutputWriter out)
{
int t = in.ni();
//int t=1;
ArrayList<Long> fact=new ArrayList<>();
long tp=2;
for(long i=3;i<15;++i)
{
tp*=i;
fact.add(tp);
}
//out.printLine(fact);
while (t-->0)
{
long n=in.nextLong();
long ans=Long.MAX_VALUE;
long len=1L<<fact.size();
for(int mask=0;mask<len;++mask)
{
long sum=n;
for(int j=0;j<fact.size();++j)
{
if((mask&(1L<<j))!=0)
{
sum-=fact.get(j);
}
}
if(sum<0)
{
continue;
}
ans=Math.min(ans,Long.bitCount(sum)+Integer.bitCount(mask));
}
out.printLine(ans);
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private char nc() { return (char)skip(); }
public int[] na(int arraySize) {
int[] array = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = ni();
}
return array;
}
private int skip() {
int b;
while ((b = read()) != -1 && isSpaceChar(b)) ;
return b;
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = read();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
int[][] nim(int h, int w) {
int[][] a = new int[h][w];
for (int i = 0; i < h; i++) {
a[i] = na(w);
}
return a;
}
long[][] nlm(int h, int w) {
long[][] a = new long[h][w];
for (int i = 0; i < h; i++) {
a[i] = nla(w);
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isNewLine(int c) {
return c == '\n';
}
public String nextLine() {
int c = read();
StringBuilder result = new StringBuilder();
do {
result.appendCodePoint(c);
c = read();
} while (!isNewLine(c));
return result.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sign = 1;
if (c == '-') {
sign = -1;
c = read();
}
long result = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
result *= 10;
result += c & 15;
c = read();
} while (!isSpaceChar(c));
return result * sign;
}
public long[] nla(int arraySize) {
long array[] = new long[arraySize];
for (int i = 0; i < arraySize; i++) {
array[i] = nextLong();
}
return array;
}
public double nextDouble() {
double ret = 0, div = 1;
byte c = (byte) read();
while (c <= ' ') {
c = (byte) read();
}
boolean neg = (c == '-');
if (neg) {
c = (byte) read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = (byte) read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = (byte) read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
public static class CP {
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n == 2 || n == 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; (long) i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
public static int log2(int N) {
int result = (int) (Math.log(N) / Math.log(2));
return result;
}
public static long pow(long a, long n, long mod) {
// a %= mod;
long ret = 1;
int x = 63 - Long.numberOfLeadingZeros(n);
for (; x >= 0; x--) {
ret = ret * ret % mod;
if (n << 63 - x < 0)
ret = ret * a % mod;
}
return ret;
}
public static boolean isComposite(long n) {
if (n < 2)
return true;
if (n == 2 || n == 3)
return false;
if (n % 2 == 0 || n % 3 == 0)
return true;
for (long i = 6L; i * i <= n; i += 6)
if (n % (i - 1) == 0 || n % (i + 1) == 0)
return true;
return false;
}
static int ifnotPrime(int[] prime, int x) {
return (prime[x / 64] & (1 << ((x >> 1) & 31)));
}
static long log2(long n)
{
return (long)(Math.log10(n)/Math.log10(2L));
}
static void makeComposite(int[] prime, int x) {
prime[x / 64] |= (1 << ((x >> 1) & 31));
}
public static String swap(String a, int i, int j) {
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
static void reverse(long arr[]){
int l = 0, r = arr.length-1;
while(l<r){
long temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
static void reverse(int arr[]){
int l = 0, r = arr.length-1;
while(l<r){
int temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
public static int[] sieveEratosthenes(int n) {
if (n <= 32) {
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int i = 0; i < primes.length; i++) {
if (n < primes[i]) {
return Arrays.copyOf(primes, i);
}
}
return primes;
}
int u = n + 32;
double lu = Math.log(u);
int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)];
ret[0] = 2;
int pos = 1;
int[] isnp = new int[(n + 1) / 32 / 2 + 1];
int sup = (n + 1) / 32 / 2 + 1;
int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
for (int tp : tprimes) {
ret[pos++] = tp;
int[] ptn = new int[tp];
for (int i = (tp - 3) / 2; i < tp << 5; i += tp)
ptn[i >> 5] |= 1 << (i & 31);
for (int j = 0; j < sup; j += tp) {
for (int i = 0; i < tp && i + j < sup; i++) {
isnp[j + i] |= ptn[i];
}
}
}
// 3,5,7
// 2x+3=n
int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4,
13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14};
int h = n / 2;
for (int i = 0; i < sup; i++) {
for (int j = ~isnp[i]; j != 0; j &= j - 1) {
int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27];
int p = 2 * pp + 3;
if (p > n)
break;
ret[pos++] = p;
if ((long) p * p > n)
continue;
for (int q = (p * p - 3) / 2; q <= h; q += p)
isnp[q >> 5] |= 1 << q;
}
}
return Arrays.copyOf(ret, pos);
}
static long digit(long s) {
long brute = 0;
while (s > 0) {
brute+=s%10;
s /= 10;
}
return brute;
}
public static int[] primefacts(int n, int[] primes) {
int[] ret = new int[15];
int rp = 0;
for (int p : primes) {
if (p * p > n) break;
int i;
for (i = 0; n % p == 0; n /= p, i++) ;
if (i > 0) ret[rp++] = p;
}
if (n != 1) ret[rp++] = n;
return Arrays.copyOf(ret, rp);
}
static ArrayList<Integer> bitWiseSieve(int n) {
ArrayList<Integer> al = new ArrayList<>();
int prime[] = new int[n / 64 + 1];
for (int i = 3; i * i <= n; i += 2) {
if (ifnotPrime(prime, i) == 0)
for (int j = i * i, k = i << 1;
j < n; j += k)
makeComposite(prime, j);
}
al.add(2);
for (int i = 3; i <= n; i += 2)
if (ifnotPrime(prime, i) == 0)
al.add(i);
return al;
}
public static long[] sort(long arr[]) {
List<Long> list = new ArrayList<>();
for (long n : arr) {
list.add(n);
}
Collections.sort(list);
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static long[] revsort(long[] arr) {
List<Long> list = new ArrayList<>();
for (long n : arr) {
list.add(n);
}
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static int[] revsort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int n : arr) {
list.add(n);
}
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
public static ArrayList<Integer> reverse(
ArrayList<Integer> data,
int left, int right)
{
// Reverse the sub-array
while (left < right)
{
int temp = data.get(left);
data.set(left++,
data.get(right));
data.set(right--, temp);
}
// Return the updated array
return data;
}
static ArrayList<Integer> sieve(long size)
{
ArrayList<Integer> pr = new ArrayList<Integer>();
boolean prime[] = new boolean[(int) size];
for (int i = 2; i < prime.length; i++) prime[i] = true;
for (int i = 2; i * i < prime.length; i++) {
if (prime[i]) {
for (int j = i * i; j < prime.length; j += i) {
prime[j] = false;
}
}
}
for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i);
return pr;
}
static boolean[] sieve1(long size) {
ArrayList<Integer> pr = new ArrayList<Integer>();
boolean prime[] = new boolean[(int) size];
for (int i = 2; i < prime.length; i++) prime[i] = true;
for (int i = 2; i * i < prime.length; i++) {
if (prime[i]) {
for (int j = i * i; j < prime.length; j += i) {
prime[j] = false;
}
}
}
//for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i);
return prime;
}
static ArrayList<Integer> segmented_sieve(int l, int r, ArrayList<Integer> primes) {
ArrayList<Integer> al = new ArrayList<>();
if (l == 1) ++l;
int max = r - l + 1;
int arr[] = new int[max];
for (int p : primes) {
if (p * p <= r) {
int i = (l / p) * p;
if (i < l) i += p;
for (; i <= r; i += p) {
if (i != p) {
arr[i - l] = 1;
}
}
}
}
for (int i = 0; i < max; ++i) {
if (arr[i] == 0) {
al.add(l + i);
}
}
return al;
}
static boolean isfPrime(long n, int iteration) {
if (n == 0 || n == 1)
return false;
if (n == 2)
return true;
if (n % 2 == 0)
return false;
Random rand = new Random();
for (int i = 0; i < iteration; i++) {
long r = Math.abs(rand.nextLong());
long a = r % (n - 1) + 1;
if (modPow(a, n - 1, n) != 1)
return false;
}
return true;
}
static long modPow(long a, long b, long c) {
long res = 1;
for (int i = 0; i < b; i++) {
res *= a;
res %= c;
}
return res % c;
}
private static long binPower(long a, long l, long mod) {
long res = 0;
while (l > 0) {
if ((l & 1) == 1) {
res = mulmod(res, a, mod);
l >>= 1;
}
a = mulmod(a, a, mod);
}
return res;
}
private static long mulmod(long a, long b, long c) {
long x = 0, y = a % c;
while (b > 0) {
if (b % 2 == 1) {
x = (x + y) % c;
}
y = (y * 2L) % c;
b /= 2;
}
return x % c;
}
static long binary_Expo(long a, long b) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1) {
res *= a;
--b;
}
a *= a;
b /= 2;
}
return res;
}
static void swap(int a, int b) {
int tp = b;
b = a;
a = tp;
}
static long Modular_Expo(long a, long b, long mod) {
long res = 1;
while (b != 0) {
if ((b & 1) == 1) {
res = (res * a) % mod;
--b;
}
a = (a * a) % mod;
b /= 2;
}
return res % mod;
}
static int i_gcd(int a, int b) {
while (true) {
if (b == 0)
return a;
int c = a;
a = b;
b = c % b;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static int gcd(int a,int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long ceil_div(long a, long b) {
return (a + b - 1) / b;
}
static int getIthBitFromInt(int bits, int i) {
return (bits >> (i - 1)) & 1;
}
static long getIthBitFromLong(long bits, int i) {
return (bits >> (i - 1)) & 1;
}
static boolean isPerfectSquare(long a)
{
long sq=(long)(Math.floor(Math.sqrt(a))*Math.floor(Math.sqrt(a)));
return sq==a;
}
private static TreeMap<Long, Long> primeFactorize(long n) {
TreeMap<Long, Long> pf = new TreeMap<>(Collections.reverseOrder());
long cnt = 0;
long total = 1;
for (long i = 2; (long) i * i <= n; ++i) {
if (n % i == 0) {
cnt = 0;
while (n % i == 0) {
++cnt;
n /= i;
}
pf.put(cnt, i);
//total*=(cnt+1);
}
}
if (n > 1) {
pf.put(1L, n);
//total*=2;
}
return pf;
}
//less than or equal
private static int lower_bound(ArrayList<Long> list, long val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(int[] arr, int val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(long[] arr, long val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid]>=val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
// greater than or equal
private static int upper_bound(List<Integer> list, int val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(int[] arr, int val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(long[] arr, long val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
// ==================== LIS & LNDS ================================
private static int[] LIS(long arr[], int n) {
List<Long> list = new ArrayList<>();
int[] cnt=new int[n];
for (int i = 0; i < n; i++) {
int idx = find1(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
cnt[i]=list.size();
}
return cnt;
}
private static int find1(List<Long> list, long val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid)>=val) {
ret = mid;
j = mid - 1;
} else {
i = mid + 1;
}
}
return ret;
}
private static int LNDS(int[] arr, int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find2(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find2(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) <= val) {
i = mid + 1;
} else {
ret = mid;
j = mid - 1;
}
}
return ret;
}
private static long nCr(long n, long r,long mod) {
if (n - r > r)
r = n - r;
long ans = 1L;
for (long i = r + 1; i <= n; i++)
ans = (ans%mod*i%mod)%mod;
for (long i = 2; i <= n - r; i++)
ans /= i;
return ans%mod;
}
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
static ArrayList<StringBuilder> permutations(StringBuilder s)
{
int n=s.length();
ArrayList<StringBuilder> al=new ArrayList<>();
getpermute(s,al,0,n);
return al;
}
// static String longestPalindrome(String s)
// {
// int st=0,ans=0,len=0;
//
//
// }
static void getpermute(StringBuilder s,ArrayList<StringBuilder> al,int l, int r)
{
if(l==r)
{
al.add(s);
return;
}
for(int i=l+1;i<r;++i)
{
char c=s.charAt(i);
s.setCharAt(i,s.charAt(l));
s.setCharAt(l,c);
getpermute(s,al,l+1,r);
c=s.charAt(i);
s.setCharAt(i,s.charAt(l));
s.setCharAt(l,c);
}
}
static void initStringHash(String s,long[] dp,long[] inv,long p)
{
long pow=1;
inv[0]=1;
int n=s.length();
dp[0]=((s.charAt(0)-'a')+1);
for(int i=1;i<n;++i)
{
pow=(pow*p)%mod;
dp[i]=(dp[i-1]+((s.charAt(i)-'a')+1)*pow)%mod;
inv[i]=CP.modinv(pow,mod)%mod;
}
}
static long getStringHash(long[] dp,long[] inv,int l,int r)
{
long ans=dp[r];
if(l-1>=0)
{
ans-=dp[l-1];
}
ans=(ans*inv[l])%mod;
return ans;
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
private static String sortString(String str) {
int[] arr = new int[256];
for (char ch : str.toCharArray())
arr[ch]++;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 256; i++)
while (arr[i]-- > 0)
sb.append((char) i);
return sb.toString();
}
static boolean isSquarefactor(int x, int factor, int target) {
int s = (int) Math.round(Math.sqrt(x));
return factor * s * s == target;
}
static boolean isSquare(long x) {
long s = (long) Math.round(Math.sqrt(x));
return x * x == s;
}
static int bs(ArrayList<Integer> al, int val) {
int l = 0, h = al.size() - 1, mid = 0, ans = -1;
while (l <= h) {
mid = (l + h) >> 1;
if (al.get(mid) == val) {
return mid;
} else if (al.get(mid) > val) {
h = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
static void sort(int a[]) // heap sort
{
PriorityQueue<Integer> q = new PriorityQueue<>();
for (int i = 0; i < a.length; i++)
q.add(a[i]);
for (int i = 0; i < a.length; i++)
a[i] = q.poll();
}
static void shuffle(int[] in) {
for (int i = 0; i < in.length; i++) {
int idx = (int) (Math.random() * in.length);
fast_swap(in, idx, i);
}
}
public static int[] radixSort2(int[] a) {
int n = a.length;
int[] c0 = new int[0x101];
int[] c1 = new int[0x101];
int[] c2 = new int[0x101];
int[] c3 = new int[0x101];
for (int v : a) {
c0[(v & 0xff) + 1]++;
c1[(v >>> 8 & 0xff) + 1]++;
c2[(v >>> 16 & 0xff) + 1]++;
c3[(v >>> 24 ^ 0x80) + 1]++;
}
for (int i = 0; i < 0xff; i++) {
c0[i + 1] += c0[i];
c1[i + 1] += c1[i];
c2[i + 1] += c2[i];
c3[i + 1] += c3[i];
}
int[] t = new int[n];
for (int v : a) t[c0[v & 0xff]++] = v;
for (int v : t) a[c1[v >>> 8 & 0xff]++] = v;
for (int v : a) t[c2[v >>> 16 & 0xff]++] = v;
for (int v : t) a[c3[v >>> 24 ^ 0x80]++] = v;
return a;
}
static int[] computeLps(String pat) {
int len = 0, i = 1, m = pat.length();
int lps[] = new int[m];
lps[0] = 0;
while (i < m) {
if (pat.charAt(i) == pat.charAt(len)) {
++len;
lps[i] = len;
++i;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = len;
++i;
}
}
}
return lps;
}
static ArrayList<Integer> kmp(String s, String pat) {
ArrayList<Integer> al = new ArrayList<>();
int n = s.length(), m = pat.length();
int lps[] = computeLps(pat);
int i = 0, j = 0;
while (i < n) {
if (s.charAt(i) == pat.charAt(j)) {
i++;
j++;
if (j == m) {
al.add(i - j);
j = lps[j - 1];
}
} else {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return al;
}
static void reverse_ruffle_sort(int a[]) {
shuffle(a);
Arrays.sort(a);
for (int l = 0, r = a.length - 1; l < r; ++l, --r)
fast_swap(a, l, r);
}
static void ruffle_sort(int a[]) {
shuffle(a);
Arrays.sort(a);
}
static int getMax(int arr[], int n) {
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
static ArrayList<Long> primeFact(long n) {
ArrayList<Long> al = new ArrayList<>();
al.add(1L);
while (n % 2 == 0) {
if (!al.contains(2L)) {
al.add(2L);
}
n /= 2L;
}
for (long i = 3; (long) i * i <= n; i += 2) {
while ((n % i == 0)) {
if (!al.contains((long) i)) {
al.add((long) i);
}
n /= i;
}
}
if (n > 2) {
if (!al.contains(n)) {
al.add(n);
}
}
return al;
}
public static long totFact(long n)
{
long cnt = 0, tot = 1;
while (n % 2 == 0) {
n /= 2;
++cnt;
}
tot *= (cnt + 1);
for (int i = 3; i <= Math.sqrt(n); i += 2) {
cnt = 0;
while (n % i == 0) {
n /= i;
++cnt;
}
tot *= (cnt + 1);
}
if (n > 2) {
tot *= 2;
}
return tot;
}
static int[] z_function(String s)
{
int n = s.length(), z[] = new int[n];
for (int i = 1, l = 0, r = 0; i < n; ++i) {
if (i <= r)
z[i] = Math.min(z[i - l], r - i + 1);
while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i]))
++z[i];
if (i + z[i] - 1 > r) {
l = i;
r = i + z[i] - 1;
}
}
return z;
}
static void fast_swap(int[] a, int idx1, int idx2) {
if (a[idx1] == a[idx2])
return;
a[idx1] ^= a[idx2];
a[idx2] ^= a[idx1];
a[idx1] ^= a[idx2];
}
public static void fast_sort(long[] array) {
ArrayList<Long> copy = new ArrayList<>();
for (long i : array)
copy.add(i);
Collections.sort(copy);
for (int i = 0; i < array.length; i++)
array[i] = copy.get(i);
}
static int factorsCount(int n) {
boolean hash[] = new boolean[n + 1];
Arrays.fill(hash, true);
for (int p = 2; p * p < n; p++)
if (hash[p] == true)
for (int i = p * 2; i < n; i += p)
hash[i] = false;
int total = 1;
for (int p = 2; p <= n; p++) {
if (hash[p]) {
int count = 0;
if (n % p == 0) {
while (n % p == 0) {
n = n / p;
count++;
}
total = total * (count + 1);
}
}
}
return total;
}
static long binomialCoeff(long n, long k) {
long res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i) {
res = (res * (n - i));
res /= (i + 1);
}
return res;
}
static long nck(long fact[], long inv[], long n, long k) {
if (k > n) return 0;
long res = fact[(int) n]%mod;
res = (int) ((res%mod* inv[(int) k]%mod))%mod;
res = (int) ((res%mod*inv[(int) (n - k)]%mod))%mod;
return res % mod;
}
public static long fact(long x) {
long fact = 1;
for (int i = 2; i <= x; ++i) {
fact = fact * i;
}
return fact;
}
public static ArrayList<Long> getFact(long x) {
ArrayList<Long> facts = new ArrayList<>();
facts.add(1L);
for (long i = 2; i * i <= x; ++i) {
if (x % i == 0) {
facts.add(i);
if (i != x / i) {
facts.add(x / i);
}
}
}
return facts;
}
static void matrix_ex(long n, long[][] A, long[][] I) {
while (n > 0) {
if (n % 2 == 0) {
Multiply(A, A);
n /= 2;
} else {
Multiply(I, A);
n--;
}
}
}
static void Multiply(long[][] A, long[][] B) {
int n = A.length, m = A[0].length, p = B[0].length;
long[][] C = new long[n][p];
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
for (int k = 0; k < m; k++) {
C[i][j] += ((A[i][k] % mod) * (B[k][j] % mod)) % mod;
C[i][j] = C[i][j] % mod;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
A[i][j] = C[i][j];
}
}
}
public static HashMap<Long, Integer> sortMapDesc(HashMap<Long,Integer> map) {
List<Map.Entry<Long, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());
HashMap<Long, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Long, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static HashMap<Character, Integer> sortMapDescch(HashMap<Character, Integer> map) {
List<Map.Entry<Character, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());
HashMap<Character, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Character, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static HashMap<Long,Long> sortMapAsclng(HashMap<Long,Long> map) {
List<Map.Entry<Long,Long>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> (int)(o1.getValue() - o2.getValue()));
HashMap<Long,Long> temp = new LinkedHashMap<>();
for (Map.Entry<Long,Long> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static HashMap<Integer, Integer> sortMapAsc(HashMap<Integer, Integer> map) {
List<Map.Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o1.getValue() - o2.getValue());
HashMap<Integer, Integer> temp = new LinkedHashMap<>();
for (Map.Entry<Integer, Integer> i : list) {
temp.put(i.getKey(), i.getValue());
}
return temp;
}
public static long lcm(long l, long l2) {
long val = gcd(l, l2);
return (l * l2) / val;
}
public static boolean isSubsequence(String s, String t) {
int n = s.length();
int m = t.length();
if (m > n) {
return false;
}
int i = 0, j = 0, skip = 0;
while (i < n && j < m) {
if (s.charAt(i) == t.charAt(j)) {
--skip;
++j;
}
++skip;
++i;
}
return j==m;
}
public static long[][] combination(int l, int r) {
long[][] pascal = new long[l + 1][r + 1];
pascal[0][0] = 1;
for (int i = 1; i <= l; ++i) {
pascal[i][0] = 1;
for (int j = 1; j <= r; ++j) {
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j];
}
}
return pascal;
}
public static long gcd(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = gcd(ret, array[i]);
return ret;
}
public static long lcm(int... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = lcm(ret, array[i]);
return ret;
}
public static int min(int a, int b) {
return a < b ? a : b;
}
public static int min(int... array) {
int ret = array[0];
for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]);
return ret;
}
public static long min(long a, long b) {
return a < b ? a : b;
}
public static long min(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]);
return ret;
}
public static int max(int a, int b) {
return a > b ? a : b;
}
public static int max(int... array) {
int ret = array[0];
for (int i = 1; i < array.length; ++i) ret = max(ret, array[i]);
return ret;
}
public static long max(long a, long b) {
return a > b ? a : b;
}
public static long max(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i) ret = max(ret, array[i]);
return ret;
}
public static long sum(int... array) {
long ret = 0;
for (int i : array) ret += i;
return ret;
}
public static long sum(long... array) {
long ret = 0;
for (long i : array) ret += i;
return ret;
}
public static long[] facts(int n,long m)
{
long[] fact=new long[n];
fact[0]=1;
fact[1]=1;
for(int i=2;i<n;i++)
{
fact[i]=(long)(i*fact[i-1])%m;
}
return fact;
}
public static long[] inv(long[] fact,int n,long mod)
{
long[] inv=new long[n];
inv[n-1]= CP.Modular_Expo(fact[n-1],mod-2,mod)%mod;
for(int i=n-2;i>=0;--i)
{
inv[i]=(inv[i+1]*(i+1))%mod;
}
return inv;
}
public static int modinv(long x, long mod) {
return (int) (CP.Modular_Expo(x, mod - 2, mod) % mod);
}
public static int lcs(String s, String t) {
int n = s.length(), m = t.length();
int dp[][] = new int[n + 1][m + 1];
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= m; ++j) {
if (i == 0 || j == 0) {
dp[i][j] = 0;
} else if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[n][m];
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void print(long[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void printLine(int[] array) {
print(array);
writer.println();
}
public void printLine(long[] array) {
print(array);
writer.println();
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
public void printLine(int i) {
writer.println(i);
}
public void printLine(char c) {
writer.println(c);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void py()
{
print("YES");
writer.println();
}
public void pn()
{
print("NO");
writer.println();
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
void flush() {
writer.flush();
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 4524a6b7a02c094512b052bef8a51a21 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static final long mod = 998244353;
static PrintWriter out = new PrintWriter(System.out);
static FastScanner sc = new FastScanner();
static long nax = (long)1e12 + 100;
static ArrayList<Long> fact = new ArrayList<>();
static void solve() {
long n = sc.nextLong();
long ans = f(0, n);
System.out.println(ans);
}
static long f(int i, long n) {
if (i == fact.size()) {
return bcount(n);
}
long res = f(i + 1, n);
if (fact.get(i) <= n)res = Math.min(res, f(i + 1, n - fact.get(i)) + 1);
return res;
}
static int bcount(long n) {
int res = 0;
for (int i = 0; i < 50; i++) {
if ((n & (1L << i)) > 0) {
res++;
}
}
return res;
}
public static void main(String[] args) {
for (long i = 1, f = 1; f <= nax; i++, f *= i) {
fact.add(f);
}
int t = 1;
t = sc.nextInt();
while (t-- > 0) {
solve();
}
out.close();
}
static void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
String readLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | b3f0d9675233336ce2f218b006f2c891 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
public class Solution{
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static long MOD = (long) (1e9 + 7);
// static long MOD = 998244353;
static long inv2 = 499122177;
static long MOD2 = MOD * MOD;
static FastReader sc = new FastReader();
static int pInf = Integer.MAX_VALUE;
static int nInf = Integer.MIN_VALUE;
static long ded = (long)(1e18)+9;
public static void main(String[] args) throws Exception {
int test = 1;
test = sc.nextInt();
f = new long[16];
f[0] = 1;
for(int i = 1; i < f.length; i++) {
f[i] = i*f[i-1];
}
// out.println(Arrays.toString(f));
for (int i = 1; i <= test; i++){
// out.print("Case #"+i+": ");
solve();
}
out.flush();
out.close();
}
static long[] f;
static void solve(){
long n = sc.nextLong();
int ans = Long.bitCount(n);
int l = f.length;
for(int i = 0; i < 1<<l; i++) {
long curr = 0L;
for(int j = 0; j < l; j++) {
if((i&(1<<j))>0){
curr += f[j];
}
}
if(curr>n)continue;
// out.print(curr+" ");
ans = Math.min(ans, Long.bitCount(i)+Long.bitCount(n-curr));
}
out.println(ans);
}
static boolean isPalin(int n) {
return n==rev(n);
}
static int rev(int n) {
int res = 0;
while(n>0) {
res = (res*10)+ n%10;
n = n/10;
}
return res;
}
static class Pair implements Comparable<Pair> {
int pos;
int idx;
public Pair(int pos, int idx) {
this.pos = pos;
this.idx = idx;
}
@Override
public int compareTo(Pair o){
// if(this.y==o.y){
// return Integer.compare((int)this.x,(int)o.x);
// }
// return Integer.compare(this.y,o.y);
if(this.pos==o.pos){
// if(this.y==o.y){
// return Integer.compare((int)this.p,(int)o.p);
// }
return Integer.compare((int)this.idx,(int)o.idx);
}
return Integer.compare(this.pos,o.pos);
}
// @Override
// public String toString() {
// return "Pair{" + "x=" + x + ", y=" + y + '}';
//// return x+" "+y;
// }
// public boolean equals(Pair o){
// return this.x==o.x&&this.y==o.y;
// }
}
static long lcm(long a, long b){
return (a*b)/gcd(a,b);
}
public static long mul(long a, long b) {
return ((a % MOD) * (b % MOD)) % MOD;
}
public static long sub(long a, long b) {
return ((a%MOD)-(b%MOD)+MOD)%MOD;
}
public static long add(long a, long b) {
if((a+b)>MOD){
return a+b-MOD;
}else{
return a+b;
}
// return ((a % MOD) + (b % MOD)) % MOD;
}
public static long c2(long n) {
if ((n & 1) == 0) {
return mul(n / 2, n - 1);
} else {
return mul(n, (n - 1) / 2);
}
}
//Shuffle Sort
static final Random random = new Random();
static void ruffleSort(int[] a) {
int n = a.length;//shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n); int temp= a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
//Brian Kernighans Algorithm
static long countSetBits(long n) {
if (n == 0) return 0;
return 1 + countSetBits(n & (n - 1));
}
//Euclidean Algorithm
static long gcd(long A, long B) {
if (B == 0) return A;
return gcd(B, A % B);
}
//Modular Exponentiation
static long fastExpo(long x, long n) {
if (n == 0) return 1;
if ((n & 1) == 0) return fastExpo((x * x) % MOD, n / 2) % MOD;
return ((x % MOD) * fastExpo((x * x) % MOD, (n - 1) / 2)) % MOD;
}
//AKS Algorithm
static boolean isPrime(long 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 <= Math.sqrt(n); i += 6)
if (n % i == 0 || n % (i + 2) == 0) return false;
return true;
}
public static long modinv(long x) {
return modpow(x, MOD - 2);
}
public static long modpow(long a, long b) {
if (b == 0) {
return 1;
}
long x = modpow(a, b / 2);
x = (x * x) % MOD;
if (b % 2 == 1) {
return (x * a) % MOD;
}
return x;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 99ffef0fb460805e9af245e0d3c0ad47 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.cert.X509CRL;
import java.util.*;
import java.lang.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
@SuppressWarnings("unused")
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static String OUTPUT = "";
//global
private final static long BASE = 998244353L;
private final static int ALPHABET = (int)('z') - (int)('a') + 1;
//private final static int BASE = 1000000007;
private final static int INF_I = (1<<31)-1;
private final static long INF_L = (1l<<63)-1;
private final static int MAXN = 200100;
private final static int MAXK = 31;
private final static int[] DX = {-1,0,1,0};
private final static int[] DY = {0,1,0,-1};
private static List<Long> data = new ArrayList<>();
static void solve() {
long tmp=1l;
for (int i=2;i<18;i++) {
data.add(tmp);
tmp = tmp*1l*i;
}
int ntest = readInt();
for (int test=0;test<ntest;test++) {
long N = readLong();
int ans = INF_I;
for (int tt=0; tt<(1<<data.size()); tt++) {
long S = 0;
int cnt = 0;
for (int i=0;i<data.size();i++)
if (((tt>>i)&1)==1) {
S += data.get(i);
cnt++;
if (S>N) break;
}
if (S>N) continue;
S = N - S;
while (S>0) {
cnt += (int)(S%2);
S/=2l;
}
ans = Math.min(ans, cnt);
}
if (ans == INF_I) out.println(-1);
else out.println(ans);
}
}
public static void main(String[] args) throws Exception
{
long S = System.currentTimeMillis();
if (INPUT=="") {
is = System.in;
} else {
File file = new File(INPUT);
is = new FileInputStream(file);
}
if (OUTPUT == "") out = new PrintWriter(System.out);
else out = new PrintWriter(OUTPUT);
solve();
out.flush();
long G = System.currentTimeMillis();
}
private static class Point<T extends Number & Comparable<T>> implements Comparable<Point<T>> {
private T x;
private T y;
public Point(T x, T y) {
this.x = x;
this.y = y;
}
public T getX() {return x;}
public T getY() {return y;}
@Override
public int compareTo(Point<T> o) {
int cmp = x.compareTo(o.getX());
if (cmp==0) return y.compareTo(o.getY());
return cmp;
}
}
private static class ClassComparator<T extends Comparable<T>> implements Comparator<T> {
public ClassComparator() {}
@Override
public int compare(T a, T b) {
return a.compareTo(b);
}
}
private static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> {
public ListComparator() {}
@Override
public int compare(List<T> o1, List<T> o2) {
for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) {
int c = o1.get(i).compareTo(o2.get(i));
if (c != 0) {
return c;
}
}
return Integer.compare(o1.size(), o2.size());
}
}
private static boolean eof()
{
if(lenbuf == -1)return true;
int lptr = ptrbuf;
while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;
try {
is.mark(1000);
while(true){
int b = is.read();
if(b == -1){
is.reset();
return true;
}else if(!isSpaceChar(b)){
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private static byte[] inbuf = new byte[1024];
static int lenbuf = 0, ptrbuf = 0;
private static int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
// private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); }
private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private static double readDouble() { return Double.parseDouble(readString()); }
private static char readChar() { return (char)skip(); }
private static String readString()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private static char[] readChar(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private static char[][] readTable(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = readChar(m);
return map;
}
private static int[] readIntArray(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = readInt();
return a;
}
private static long[] readLongArray(int n) {
long[] a = new long[n];
for (int i=0;i<n;i++) a[i] = readLong();
return a;
}
private static int readInt()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static long readLong()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 6b7c90a4fd7a634cf66f0183dcd2899b | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes |
import java.io.*;
import java.util.*;
public class cp {
static int mod=(int)1e9+7;
// static Reader sc=new Reader();
static FastReader sc=new FastReader(System.in);
static int[] sp;
static int size=(int)1e6;
static int[] arInt;
static long[] arLong;
static long ans;
public static void main(String[] args) throws IOException {
long tc=sc.nextLong();
// Scanner sc=new Scanner(System.in);
// int tc=1;
// print_int(pre);
// primeSet=new HashSet<>();
// primeCnt=new int[(int)1e9];
// sieveOfEratosthenes((int)1e9);
// factorial(mod);
// InverseofNumber(mod);
// InverseofFactorial(mod);
long fact[]=new long[20];
fact[1]=1L;
for(long i=2;i<16;i++)
{
fact[(int)i]=i*fact[(int)i-1];
}
// print(fact);
while(tc-->0)
{
long n=sc.nextLong();
int ans=60;
for(int i=0;i<(1<<16);i++)
{
long sum=0;
int k=0;
for(int j=0;j<16;j++)
{
if((i & (1<<j))!=0)
{
k++;
sum+=fact[j+1];
}
}
ans=Math.min(ans, k+popc(n-sum));
}
out.println(ans);
}
// System.out.flush();
out.flush();
out.close();
System.gc();
}
/*
...SOLUTION ENDS HERE...........SOLUTION ENDS HERE...
*/
static long f(long x){
return x&(-x);
}
static int popc(long x){
if(x<0) return 60;
int rt=0;
while(x>0){
x-=f(x);
rt++;
}
return rt;
}
static boolean wordPattern(String pattern, String s) {
String[] arr=s.split("\\s+");
ArrayList<Integer> a[]=new ArrayList[26];
for(int i=0;i<26;i++)
a[i]=new ArrayList<>();
for(String e:arr)
out.println(e);
for(int i=0;i<pattern.length();i++)
{
int idx=(int)(pattern.charAt(i)-'a');
a[idx].add(i);
}
// for(ArrayList<Integer> e:a)
// print_int(e);
for(int i=0;i<26;i++)
{
if(a[i].size()==0)
continue;
String temp=arr[a[i].get(0)];
out.println(temp);
for(int idx:a[i])
{
out.println(idx);
if(!arr[idx].equals(temp))
return false;
}
}
return true;
}
static long binomialCoeff(int n, int k,long dp[][])
{
// Base Cases
if (k > n)
return 0;
if (k == 0 || k == n)
return dp[n][k]=1;
if(dp[n][k]!=-1)
return dp[n][k];
// Recur
return dp[n][k]=binomialCoeff(n - 1, k - 1,dp) + binomialCoeff(n - 1, k,dp);
}
static void reverseList(ArrayList<Integer> a)
{
int i=0,j=a.size()-1;
while(i<j)
{
int temp=a.get(i);
a.set(i, a.get(j));
a.set(j, temp);
i++;
j--;
}
}
static void util(int x,int[] a,int[] ans,boolean[] vis,ArrayList<Pair> rem)
{
int curr=x;
while(true)
{
vis[curr]=true;
if(vis[a[curr]])
{
rem.add(new Pair(x, curr));
break;
}
ans[curr]=a[curr];
curr=a[curr];
}
}
static void util2(int x,int[] a,int[] ans,boolean[] vis,ArrayList<Pair> rem)
{
for(int i=1;i<ans.length;i++)
{
ans[i]=a[i];
}
int total=rem.size();
for(int i=0;i<rem.size();i++)
{
int nxt=(i+1)%total;
ans[rem.get(i).y]=rem.get(nxt).x;
}
}
static long lcm(long x,long y)
{
return x/gcd(x,y)*y;
}
static class Node{
int a;
ArrayList<Pair> adj;
public Node(int a) {
this.a=a;
this.adj=new ArrayList<>();
}
}
static void dijkstra(Node[] g,int dist[],int parent[],int src)
{
Arrays.fill(dist, int_max);
Arrays.fill(parent, -1);
boolean vis[]=new boolean[dist.length];
// vis[1]=true;
PriorityQueue<Pair> q=new PriorityQueue<>();
q.add(new Pair(1, 0));
dist[1]=0;
while(!q.isEmpty())
{
Pair curr=q.poll();
vis[curr.x]=true;
for(Pair edge:g[curr.x].adj)
{
if (vis[edge.x]) {
continue;
}
if (dist[edge.x]>dist[curr.x]+edge.y) {
dist[edge.x]=dist[curr.x]+edge.y;
parent[edge.x]=curr.x;
q.add(new Pair(edge.x, dist[edge.x]));
}
}
}
}
static void mapping(int a[])
{
Pair[] temp=new Pair[a.length];
for (int i = 0; i < temp.length; i++) {
temp[i]=new Pair(a[i], i);
}
Arrays.sort(temp);
int k=0;
for (int i = 0; i < temp.length; i++) {
a[temp[i].y]=k++;
}
}
static boolean palin(String s)
{
for(int i=0;i<s.length()/2;i++)
if(s.charAt(i)!=s.charAt(s.length()-i-1))
return false;
return true;
}
static class temp implements Comparable<temp>{
int x;
int y;
int sec;
public temp(int x,int y,int l) {
// TODO Auto-generated constructor stub
this.x=x;
this.y=y;
this.sec=l;
}
@Override
public int compareTo(temp o) {
// TODO Auto-generated method stub
return this.sec-o.sec;
}
}
// static class Node{
// int x;
// int y;
// ArrayList<Integer> edges;
// public Node(int x,int y) {
// // TODO Auto-generated constructor stub
// this.x=x;
// this.y=y;
// this.edges=new ArrayList<>();
// }
// }
static int lis(int arr[],int n)
{
int ans=0;
int dp[]=new int[n+1];
Arrays.fill(dp, int_max);
dp[0]=int_min;
for(int i=0;i<n;i++)
{
int j=UpperBound(dp,arr[i]);
if(dp[j-1]<=arr[i] && arr[i]<dp[j])
dp[j]=arr[i];
}
for(int i=0;i<=n;i++)
{
if(dp[i]<int_max)
ans=i;
}
return ans;
}
static long get(long n)
{
return n*(n+1)/2L;
}
static boolean go(ArrayList<Pair> caves,int k)
{
for(Pair each:caves)
{
if(k<=each.x)
return false;
k+=each.y;
}
return true;
}
static String revString(String s)
{
char arr[]=s.toCharArray();
int n=s.length();
for(int i=0;i<n/2;i++)
{
char temp=arr[i];
arr[i]=arr[n-i-1];
arr[n-i-1]=temp;
}
return String.valueOf(arr);
}
// Fuction return the number of set bits in n
static int SetBits(int n)
{
int cnt=0;
while(n>0)
{
if((n&1)==1)
{
cnt++;
}
n=n>>1;
}
return cnt;
}
static boolean isPowerOfTwo(int n)
{
return (int)(Math.ceil((Math.log(n) / Math.log(2))))
== (int)(Math.floor(((Math.log(n) / Math.log(2)))));
}
static void arrInt(int n) throws IOException
{
arInt=new int[n];
for (int i = 0; i < arInt.length; i++) {
arInt[i]=sc.nextInt();
}
}
static void arrLong(int n) throws IOException
{
arLong=new long[n];
for (int i = 0; i < arLong.length; i++) {
arLong[i]=sc.nextLong();
}
}
static ArrayList<Integer> add(int id,int c)
{
ArrayList<Integer> newArr=new ArrayList<>();
for(int i=0;i<id;i++)
newArr.add(arInt[i]);
newArr.add(c);
for(int i=id;i<arInt.length;i++)
{
newArr.add(arInt[i]);
}
return newArr;
}
// function to find first index >= y
static int upper(ArrayList<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (h-l>1)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= x)
l=mid+1;
else
{
h=mid;
}
}
if(arr.get(l)>x)
{
return l;
}
if(arr.get(h)>x)
return h;
return -1;
}
static int upper(ArrayList<Long> arr, int n, long x)
{
int l = 0, h = n - 1;
while (h-l>1)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= x)
l=mid+1;
else
{
h=mid;
}
}
if(arr.get(l)>x)
{
return l;
}
if(arr.get(h)>x)
return h;
return -1;
}
static int lower(ArrayList<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (h-l>1)
{
int mid = (l + h) / 2;
if (arr.get(mid) < x)
l=mid+1;
else
{
h=mid;
}
}
if(arr.get(l)>=x)
{
return l;
}
if(arr.get(h)>=x)
return h;
return -1;
}
static int N = (int)2e5+5;
// Array to store inverse of 1 to N
static long[] factorialNumInverse = new long[N + 1];
// Array to precompute inverse of 1! to N!
static long[] naturalNumInverse = new long[N + 1];
// Array to store factorial of first N numbers
static long[] fact = new long[N + 1];
// Function to precompute inverse of numbers
public static void InverseofNumber(int p)
{
naturalNumInverse[0] = naturalNumInverse[1] = 1;
for(int i = 2; i <= N; i++)
naturalNumInverse[i] = naturalNumInverse[p % i] *
(long)(p - p / i) % p;
}
// Function to precompute inverse of factorials
public static void InverseofFactorial(int p)
{
factorialNumInverse[0] = factorialNumInverse[1] = 1;
// Precompute inverse of natural numbers
for(int i = 2; i <= N; i++)
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i - 1]) % p;
}
// Function to calculate factorial of 1 to N
public static void factorial(int p)
{
fact[0] = 1;
// Precompute factorials
for(int i = 1; i <= N; i++)
{
fact[i] = (fact[i - 1] * (long)i) % p;
}
}
// Function to return nCr % p in O(1) time
public static long Binomial(int N, int R, long p)
{
// n C r = n!*inverse(r!)*inverse((n-r)!)
long ans = ((fact[N] * factorialNumInverse[R]) %
p * factorialNumInverse[N - R]) % p;
return ans;
}
static String tr(String s)
{
int now = 0;
while (now + 1 < s.length() && s.charAt(now)== '0')
++now;
return s.substring(now);
}
static boolean isPrime(long n)
{
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
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;
}
static ArrayList<Integer> commDiv(int a, int b)
{
// find gcd of a, b
int n = gcd(a, b);
// Count divisors of n.
ArrayList<Integer> Div=new ArrayList<>();
for (int i = 1; i <= Math.sqrt(n); i++) {
// if 'i' is factor of n
if (n % i == 0) {
// check if divisors are equal
if (n / i == i)
Div.add(i);
else
{
Div.add(i);
Div.add(n/i);
}
}
}
return Div;
}
static HashSet<Integer> factors(int x)
{
HashSet<Integer> a=new HashSet<Integer>();
for(int i=2;i*i<=x;i++)
{
if(x%i==0)
{
a.add(i);
a.add(x/i);
}
}
return a;
}
static void primeFactors(int n,HashSet<Integer> factors)
{
// Print the number of 2s that divide n
while (n%2==0)
{
factors.add(2);
n /= 2;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
factors.add(i);
n /= i;
}
}
// This condition is to handle the case when
// n is a prime number greater than 2
if (n > 2)
factors.add(n);
}
static class Tuple{
int a;
int b;
int c;
public Tuple(int a,int b,int c) {
this.a=a;
this.b=b;
this.c=c;
}
}
//function to find prime factors of n
static HashMap<Long,Long> findFactors(long n2)
{
HashMap<Long,Long> ans=new HashMap<>();
if(n2%2==0)
{
ans.put(2L, 0L);
// cnt++;
while((n2&1)==0)
{
n2=n2>>1;
ans.put(2L, ans.get(2L)+1);
//
}
}
for(long i=3;i*i<=n2;i+=2)
{
if(n2%i==0)
{
ans.put((long)i, 0L);
// cnt++;
while(n2%i==0)
{
n2=n2/i;
ans.put((long)i, ans.get((long)i)+1);
}
}
}
if(n2!=1)
{
ans.put(n2, ans.getOrDefault(n2, (long) 0)+1);
}
return ans;
}
//fenwick tree implementaion
static class fwt
{
int n;
long BITree[];
fwt(int n)
{
this.n=n;
BITree=new long[n+1];
}
fwt(int arr[], int n)
{
this.n=n;
BITree=new long[n+1];
for(int i = 0; i < n; i++)
updateBIT(n, i, arr[i]);
}
long getSum(int index)
{
long sum = 0;
index = index + 1;
while(index>0)
{
sum += BITree[index];
index -= index & (-index);
}
return sum;
}
void updateBIT(int n, int index,int val)
{
index = index + 1;
while(index <= n)
{
BITree[index] += val;
index += index & (-index);
}
}
long sum(int l, int r) {
return getSum(r) - getSum(l - 1);
}
void print()
{
for(int i=0;i<n;i++)
out.print(getSum(i)+" ");
out.println();
}
}
static class sparseTable{
int n;
long[][]dp;
int log2[];
int P;
void buildTable(long[] arr)
{
n=arr.length;
P=(int)Math.floor(Math.log(n)/Math.log(2));
log2=new int[n+1];
log2[0]=log2[1]=0;
for(int i=2;i<=n;i++)
{
log2[i]=log2[i/2]+1;
}
dp=new long[P+1][n];
for(int i=0;i<n;i++)
{
dp[0][i]=arr[i];
}
for(int p=1;p<=P;p++)
{
for(int i=0;i+(1<<p)<=n;i++)
{
long left=dp[p-1][i];
long right=dp[p-1][i+(1<<(p-1))];
dp[p][i]=Math.min(left, right);
}
}
}
long maxQuery(int l,int r)
{
int len=r-l+1;
int p=(int)Math.floor(log2[len]);
long left=dp[p][l];
long right=dp[p][r-(1<<p)+1];
return Math.min(left,right);
}
}
//Function to find number of set bits
static int setBitNumber(long n)
{
if (n == 0)
return 0;
int msb = 0;
n = n / 2;
while (n != 0) {
n = n / 2;
msb++;
}
return msb;
}
static int getFirstSetBitPos(long n)
{
return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;
}
static ArrayList<Integer> primes;
static HashSet<Integer> primeSet;
static boolean prime[];
static int primeCnt[];
static void sieveOfEratosthenes(int n)
{
prime= new boolean[n + 1];
for (int i = 2; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int i = 2; i <= n; i++)
{
if (prime[i] == true)
primeCnt[i]=primeCnt[i-1]+1;
}
}
static long mod(long a, long b) {
long c = a % b;
return (c < 0) ? c + b : c;
}
static void swap(long arr[],int i,int j)
{
long temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
static boolean util(int a,int b,int c)
{
if(b>a)util(b, a, c);
while(c>=a)
{
c-=a;
if(c%b==0)
return true;
}
return (c%b==0);
}
static void flag(boolean flag)
{
out.println(flag ? "YES" : "NO");
out.flush();
}
static void print(int a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print(long a[])
{
int n=a.length;
for(int i=0;i<n;i++)
{
out.print(a[i]+" ");
}
out.println();
out.flush();
}
static void print_int(ArrayList<Integer> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void print_long(ArrayList<Long> al)
{
int si=al.size();
for(int i=0;i<si;i++)
{
out.print(al.get(i)+" ");
}
out.println();
out.flush();
}
static void printYesNo(boolean condition)
{
if (condition) {
out.println("YES");
}
else {
out.println("NO");
}
}
static int LowerBound(int a[], int x)
{ // x is the target value or key
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
static int lowerIndex(int arr[], int n, int x)
{
int l = 0, h = n - 1;
while (l<=h)
{
int mid = (l + h) / 2;
if (arr[mid] >= x)
h = mid -1 ;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
static int upperIndex(int arr[], int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
static int upperIndex(long arr[], int n, long y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
static int UpperBound(int a[], int x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static int UpperBound(long a[], long x)
{// x is the key or target value
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
static class DisjointUnionSets
{
int[] rank, parent;
int n;
// Constructor
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
// Creates n sets with single item in each
void makeSet()
{
for (int i = 0; i < n; i++)
parent[i] = i;
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
// Unites the set that includes x and the set
// that includes x
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else // if ranks are the same
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
// if(xRoot!=yRoot)
// parent[y]=x;
}
int connectedComponents()
{
int cnt=0;
for(int i=0;i<n;i++)
{
if(parent[i]==i)
cnt++;
}
return cnt;
}
}
// static class Graph
// {
// int v;
// ArrayList<Integer> list[];
// Graph(int v)
// {
// this.v=v;
// list=new ArrayList[v+1];
// for(int i=1;i<=v;i++)
// list[i]=new ArrayList<Integer>();
// }
// void addEdge(int a, int b)
// {
// this.list[a].add(b);
// }
//
//
//
// }
static class Pair implements Comparable<Pair>
{
int x;
int y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
@Override
public int compareTo(Pair o) {
// TODO Auto-generated method stub
return this.y-o.y;
}
}
static class PairL implements Comparable<PairL>
{
long x;
long y;
PairL(long x,long y)
{
this.x=x;
this.y=y;
}
@Override
public int compareTo(PairL o) {
// TODO Auto-generated method stub
return (this.y>o.y)?1:-1;
}
}
static long sum_array(int a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static long sum_array(long a[])
{
int n=a.length;
long sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
static void sort(int[] a)
{
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void revSort(long arr[])
{
ArrayList<Long> a=new ArrayList<Long>();
for (int i = 0; i < arr.length; i++) {
a.add(arr[i]);
}
// Collections.sort(a);
Collections.sort(a,Comparator.reverseOrder());
for (int i = 0; i < arr.length; i++) {
arr[i]=a.get(i);
}
}
static void reverse_array(int a[])
{
int n=a.length;
int i,t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
static void reverse_array(long a[])
{
int n=a.length;
int i; long t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
}
// static long modInverse(long a, long m)
// {
// long g = gcd(a, m);
//
// return power(a, m - 2, m);
//
// }
static long power(long x, long y)
{
long res = 1;
x = x % mod;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % mod;
y = y >> 1; // y = y/2
x = (x * x) % mod;
}
return res;
}
static int power(int x, int y)
{
int res = 1;
x = x % mod;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % mod;
y = y >> 1; // y = y/2
x = (x * x) % mod;
}
return res;
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
//cnt+=a/b;
return gcd(b%a,a);
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static class FastReader{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static PrintWriter out=new PrintWriter(System.out);
static int int_max=Integer.MAX_VALUE;
static int int_min=Integer.MIN_VALUE;
static long long_max=Long.MAX_VALUE;
static long long_min=Long.MIN_VALUE;
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 21c632a0f1bb3a6af0fe20ad3a0b6de9 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class App {
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static void solve(FastReader reader, PrintWriter writer, long[] factorials) {
long n = reader.nextLong();
int min = Integer.MAX_VALUE;
for (int i = (1 << 15) - 1; i >= 0; i--) {
long sum = 0;
int steps = 0;
for (int j = 0; j < 15; j++) {
if ((i & (1 << j)) > 0) {
sum += factorials[j];
steps++;
}
}
if (sum <= n) min = Math.min(min, Long.bitCount(n - sum) + steps);
}
writer.println(min);
}
public static void main(String[] args){
FastReader reader = new FastReader();
PrintWriter writer = new PrintWriter(System.out, true);
int t = reader.nextInt();
long[] factorials = new long[15];
factorials[0] = 1;
factorials[1] = 1;
for (int i = 2; i < 15; i++) {
factorials[i] = i * factorials[i - 1];
}
// int t = 1;
for (int i = 1; i <= t; i++) {
solve(reader, writer, factorials);
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 5dbf5bc8ff3f1ce0c22d1d077e500b59 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class C {
static ArrayList<Long> facs = new ArrayList<>();
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(reader.readLine());
facs.add(6L);
long max = 1_000_000_000_000L;
long last = 2;
for(int i = 3; i < 20; i++) {
long num = last * i;
double log = Math.log(num) / Math.log(2);
if (log - Math.floor(log) > 0)
facs.add(num);
if (num > max) {
break;
}
last = num;
}
for(int t = 0; t < T; t++) {
long num = Long.parseLong(reader.readLine());
long res = rec(num, 0);
System.out.println(res);
}
}
private static long rec(long num, int index) {
if (index < facs.size() && num >= facs.get(index)) {
long a = rec(num - facs.get(index), index + 1) + 1;
long b = rec(num, index + 1);
return Math.min(a, b);
}
return countOnes(num);
}
private static long countOnes(long num) {
char[] bin = Long.toBinaryString(num).toCharArray();
long count = 0;
for(int i = 0; i < bin.length; i++) {
if (bin[i] == '1')
count += 1;
}
return count;
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | f910dafa7c83841ef9a6d2148a4e244d | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.*;
public class PowerOfTwo {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
StringBuffer str = new StringBuffer("");
long arr[] = new long[12];
long pow[] = new long[51];
pow[0] = 1;
for(int i = 1 ; i <= 50 ; i++) {
pow[i] = pow[i - 1] * 2;
}
int cnt[] = new int[1 << 12];
arr[0] = 6;
for(int i = 1 ; i <= 11 ; i++) {
arr[i] = arr[i - 1] * (long)(i + 3);
}
long sum[] = new long[1 << 12];
for(int i = 0 ; i < 1 << 12 ; i++)
{
for(int j = 0 ; j < 12 ; j++)
{
if((i & (1 << j)) > 0)
{
sum[i] += arr[j];
cnt[i]++;
}
}
}
while(t-- > 0)
{
long n = s.nextLong();
int min = 100;
for(int i = 0 ; i < 1 << 12 ; i++)
{
long x = sum[i];
if(n-x >= 0)
{
long y = n -x;
int tot = 0;
for(int j = 0 ; j <= 50 ; j++)
{
if((y&(pow[j])) > 0)
tot++;
}
min = Math.min(min, cnt[i] + tot);
}
}
System.out.println(min);
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 5289a1f43201555368b2a64dca73ca7e | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
*
* @author ken
*/
public class FactorialsAndPowersOfTwo {
static long[] factorials = new long[15];
public static long sums(boolean[] arr) {
long sum = 0;
for (int i = 3; i < 15; i++) {
if (arr[i]) {
sum += factorials[i];
}
}
return sum;
}
public static long ones(long n) {
long count = Long.bitCount(n);
return count;
}
public static void main(String[] args) {
Kattio io = new Kattio();
int t = io.nextInt();
for (int a = 0; a < t; a++) {
long n = io.nextLong();
factorials[0] = 1;
factorials[1] = 1;
for (int i = 2; i < 15; i++) {
factorials[i] = factorials[i - 1] * i;
}
//
long minK = Long.MAX_VALUE;
for (int i = 0; i < Math.pow(2, 15); i++) {
String bin = Integer.toBinaryString(i);
while (bin.length() < 15) {
bin = "0" + bin;
}
char[] chars = bin.toCharArray();
boolean[] boolArray = new boolean[15];
for (int j = 0; j < chars.length; j++) {
boolArray[j] = chars[j] == '0' ? true : false;
}
int f = 0;
for (int j = 3; j < 15; j++) {
if (boolArray[j]) {
f++;
}
}
minK = Math.min(f + ones(n - sums(boolArray)), minK);
}
System.out.println(minK);
}
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio() {
this(System.in, System.out);
}
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(problemName + ".out");
r = new BufferedReader(new FileReader(problemName + ".in"));
}
// returns null if no more input
public String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(r.readLine());
}
return st.nextToken();
} catch (Exception e) {
}
return null;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 758b51254616d2155b1f5bd338c402f2 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.*;
import java.lang.*;
import java.util.*;
public class Main {
public static int mod = (int) 1e9 + 7;
// **** -----> Disjoint Set Union(DSU) Start **********
public static int findPar(int node, int[] parent) {
if (parent[node] == node)
return node;
return parent[node] = findPar(parent[node], parent);
}
public static boolean union(int u, int v, int[] rank, int[] parent) {
u = findPar(u, parent);
v = findPar(v, parent);
if(u == v) return false;
if (rank[u] < rank[v])
parent[u] = v;
else if (rank[u] > rank[v])
parent[v] = u;
else {
parent[u] = v;
rank[v]++;
}
return true;
}
// **** DSU Ends ***********
//Pair with int int
public static class Pair{
public int a;
public int b;
Pair(int a , int b){
this.a = a;
this.b = b;
}
@Override
public String toString(){
return a + " -> " + b;
}
}
public static String toBinary(int decimal) {StringBuilder sb = new StringBuilder();while (decimal > 0) {sb.append(decimal % 2);decimal = decimal / 2;}return sb.reverse().toString();}
public static boolean isPalindrome(String s) {int i = 0, j = s.length() - 1;while (i < j) {if (s.charAt(i) != s.charAt(j))return false;i++;j--;}return true;}
public static boolean isPalindrome(int[] arr) {int i = 0, j = arr.length - 1;while (i < j) {if (arr[i] != arr[j])return false;}return true;}
public static int pow(int x, int y) {int res = 1;x = x % mod;if (x == 0)return 0;while (y > 0) {if ((y & 1) != 0)res = (res * x) % mod;y = y >> 1;x = (x * x) % mod;}return res;}
public static int gcd(int a, int b) {if (b == 0)return a;return gcd(b, a % b);}
public static long gcd(long a, long b) {if (b == 0)return a;return gcd(b, a % b);}
public static void sort(long[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);long temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);}
public static void reverse(int a[]) {int i, k, t, n = a.length;for (i = 0; i < n / 2; i++) {t = a[i];a[i] = a[n - i - 1];a[n - i - 1] = t;}}
public static void sort(int[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);int temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);}
public static void revSort(int[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);int temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);reverse(a);}
public static long LCM(long a, long b) {if (a > b) {long t = a;a = b;b = t;}a /= gcd(a, b);return (a * b);}
public static int findMax(int[] a, int left, int right) {int res = left;int max = a[left];for (int i = left + 1; i <= right; i++) {if (a[i] > max) {max = a[i];res = i;}}return res;}
public static long findClosest(long arr[], long target) {int n = arr.length;if (target <= arr[0])return arr[0];if (target >= arr[n - 1])return arr[n - 1];int i = 0, j = n, mid = 0;while (i < j) {mid = (i + j) / 2;if (arr[mid] == target)return arr[mid];if (target < arr[mid]) {if (mid > 0 && target > arr[mid - 1])return getClosest(arr[mid - 1], arr[mid], target);j = mid;} else {if (mid < n - 1 && target < arr[mid + 1])return getClosest(arr[mid], arr[mid + 1], target);i = mid + 1;}}return arr[mid];}
public static long getClosest(long val1, long val2, long target) {if (target - val1 >= val2 - target)return val2;else return val1;}
public static int findClosest(int arr[], int target) { int n = arr.length; if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid];if (target < arr[mid]) {if (mid > 0 && target > arr[mid - 1])return getClosest(arr[mid - 1], arr[mid], target);j = mid;} else {if (mid < n - 1 && target < arr[mid + 1])return getClosest(arr[mid], arr[mid + 1], target);i = mid + 1;}}return arr[mid];}
public static int getClosest(int val1, int val2, int target) {if (target - val1 >= val2 - target)return val2;else return val1;}
public static String reverse(String str) {String nstr = "";char ch;for (int i = 0; i < str.length(); i++) {ch = str.charAt(i);nstr = ch + nstr;}return nstr;}
public static boolean 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;}
public static int xorSum(int arr[], int n){int bits = 0;for (int i = 0; i < n; ++i)bits |= arr[i];int ans = bits * (int)Math.pow(2, n-1);return ans;}
public static ArrayList<Integer> primeFactors(int n) { ArrayList<Integer> res = new ArrayList<>();while (n%2 == 0) { res.add(2); n = n/2; } for (int i = 3; i <= Math.sqrt(n); i = i+2) { while (n%i == 0) { res.add(i); n = n/i; } } if (n > 2) res.add(n);return res;}
public static ArrayList<Long> primeFactors(long n) { ArrayList<Long> res = new ArrayList<>();while (n%2 == 0) { res.add(2L); n = n/2; } for (long i = 3; i <= Math.sqrt(n); i = i+2) { while (n%i == 0) { res.add(i); n = n/i; } } if (n > 2) res.add(n);return res;}
static int lower_bound(int array[], int low, int high, int key){
int mid;
while (low < high) {
mid = low + (high - low) / 2;
if (key <= array[mid]) high = mid;
else low = mid + 1;
}
if (low < array.length && array[low] < key) low++;
return low;
}
/********************************* Start Here ***********************************/
// int mod = 1000000007;
// static HashMap<Integer, HashMap<Long, Integer>> map;
public static void main(String[] args) throws java.lang.Exception {
if (System.getProperty("ONLINE_JUDGE") == null) {
PrintStream ps = new PrintStream(new File("output.txt"));
System.setOut(ps);
}
FastScanner sc = new FastScanner("input.txt");
int T = sc.nextInt();
// int T = 1;
while (T-- > 0) {
long n = sc.nextLong();
List<Long> pnums = new ArrayList<>();
long num = 1l;
for(int i = 0; i < 15; i++){
num *= (i+1);
pnums.add(num);
}
minCount = Integer.MAX_VALUE;
helper(pnums,0,0l,0,n);
System.out.println(minCount);
}
System.out.close();
}
static int minCount = Integer.MAX_VALUE;
public static void helper(List<Long> nums, int index, long sum, int cnt, long n){
if(index >= nums.size() || sum > n){
return;
}
minCount = Math.min(minCount,find(sum,n,cnt));
helper(nums,index+1,sum,cnt,n);
helper(nums,index+1,sum+nums.get(index),cnt+1,n);
}
public static int find(long sum, long n, int cnt){
int ans = cnt;
n -= sum;
for(int i = 0; i < 64; i++){
if((n & (1l << i)) != 0){
ans++;
}
}
return ans;
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() {
if (st == null || !st.hasMoreTokens()) {
try {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken("\n");
}
public String[] readStringArray(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) {
a[i] = next();
}
return a;
}
int nextInt() {
return Integer.parseInt(nextToken());
}
String next() {
return nextToken();
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] read2dArray(int n, int m) {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = nextInt();
}
}
return a;
}
long[][] read2dlongArray(int n, int m) {
long[][] a = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = nextLong();
}
}
return a;
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 11 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 50ded63016ea7e17c4e4ea063e068950 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes |
import java.lang.reflect.Array;
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
public static FastReader cin;
public static PrintWriter out;
public static void main(String[] args) throws Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
cin = new FastReader();
long [] T = new long [20];
T[0] = 1;
for(int i = 1 ; i < 20 ; i++){
T[i] = T[i-1]*i;
// out.printf("T[%d]=%d\n",i,T[i]);
}
int qq = cin.nextInt();
// int qq = 1;
label:while (qq-- > 0) {
Long n = cin.nextLong();
int total = 1<<16;
int ans = Long.bitCount(n);
for(int i = 0 ; i < total ; i++){
long cur = 0;
for(int j = 0 ; j < 16;j++){
if(((1 << j)&i)==0){
continue;
}
cur+=T[j];
}
if(cur>n)continue;
int temp = Integer.bitCount(i) + Long.bitCount(n - cur);
ans = Integer.min(ans,temp);
}
out.println(ans);
}
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer str;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (str == null || !str.hasMoreElements()) {
try {
str = new StringTokenizer(br.readLine());
} catch (IOException lastMonthOfVacation) {
lastMonthOfVacation.printStackTrace();
}
}
return str.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException lastMonthOfVacation) {
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 17 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 44b9131d100c39a4c89398175b64ba67 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class Round774C {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
Round774C sol = new Round774C();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
boolean hasMultipleTests = true;
initIO(isFileIO);
preprocess(1_000_000_000_000L);
int t = hasMultipleTests? in.nextInt() : 1;
for (int i = 1; i <= t; ++i) {
long n = in.nextLong();
if(isDebug){
out.printf("Test %d\n", i);
}
int ans = solve(n);
out.printlnAns(ans);
if(isDebug)
out.flush();
}
in.close();
out.close();
}
private int solve(long n) {
int k = rec(n, fac.size());
return k;
}
private int rec(long n, int maxFacIndex) {
if(dp.containsKey(pack(n, maxFacIndex)))
return dp.get(pack(n, maxFacIndex));
if(n == 0)
return 0;
int min = Long.bitCount(n);
for(int i=maxFacIndex-1; i>=0; i--) {
if(fac.get(i) <= n) {
min = Math.min(min, 1+rec(n-fac.get(i), i));
}
}
dp.put(pack(n, maxFacIndex), min);
return min;
}
private Long pack(long n, int index) {
long ret = n << 6;
ret += index;
return ret;
}
HashMap<Long, Integer> dp;
private void preprocess(long MAX) {
long curr = 6; // exclude 1, 2
long index = 4;
fac = new ArrayList<>();
while(curr <= MAX) {
fac.add(curr);
curr *= index;
index++;
}
dp = new HashMap<>();
}
ArrayList<Long> fac;
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[][] nextTreeEdges(int n, int offset){
int[][] e = new int[n-1][2];
for(int i=0; i<n-1; i++){
e[i][0] = nextInt()+offset;
e[i][1] = nextInt()+offset;
}
return e;
}
int[][] nextMatrix(int n, int m) {
return nextMatrix(n, m, 0);
}
int[][] nextMatrix(int n, int m, int offset) {
int[][] mat = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[i][j] = nextInt()+offset;
}
}
return mat;
}
int[][] nextPairs(int n){
return nextPairs(n, 0);
}
int[][] nextPairs(int n, int offset) {
int[][] xy = new int[2][n];
for(int i=0; i<n; i++) {
xy[0][i] = nextInt() + offset;
xy[1][i] = nextInt() + offset;
}
return xy;
}
int[][] nextGraphEdges(){
return nextGraphEdges(0);
}
int[][] nextGraphEdges(int offset) {
int m = nextInt();
int[][] e = new int[m][2];
for(int i=0; i<m; i++){
e[i][0] = nextInt()+offset;
e[i][1] = nextInt()+offset;
}
return e;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
public void printlnAns(long ans) {
println(ans);
}
public void printlnAns(int ans) {
println(ans);
}
public void printlnAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
printAns(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
printAns(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(long[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private void permutateAndSort(long[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
long temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private void permutateAndSort(int[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
int temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
int[] inIdx = new int[n];
int[] outIdx = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][outIdx[u]++] = v;
inNeighbors[v][inIdx[v]++] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
int[] idx = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][idx[u]++] = v;
neighbors[v][idx[v]++] = u;
}
return neighbors;
}
static private void drawGraph(int[][] e) {
makeDotUndirected(e);
try {
final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
.redirectOutput(new File("graph.png"))
.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 17 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 2681932c02c3654187ba7dae0d9d2cee | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | /******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.util.*;
public class Main
{
public static boolean issorted(int []arr){
for(int i = 1;i<arr.length;i++){
if(arr[i]<arr[i-1]){
return false;
}
}
return true;
}
public static boolean ispalin(StringBuilder sb){
int i = 0;
int j = sb.length()-1;
while(i<=j){
if(sb.charAt(i) != sb.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
public static long sum(int []arr){
long sum = 0;
for(int i = 0;i<arr.length;i++){
sum+=arr[i];
}
return sum;
}
public static class pair{
long x;
long y;
pair(long x,long y){
this.x = x;
this.y = y;
}
}
public static void swap(int []arr,int i,int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static int gcd(int a, int b){
if (b == 0)
return a;
return gcd(b, a % b);
}
static int []parent = new int[1000];
static int []size = new int[1000];
public static void make(int v){
parent[v] = v;
size[v] = 1;
}
public static int find(int v){
if(parent[v]==v){
return v;
}
else{
return parent[v] = find(parent[v]);
}
}
public static void union(int a,int b){
a = find(a);
b = find(b);
if(a!=b){
if(size[a]>size[b]){
parent[b] = parent[a];
size[b]+=size[a];
}
else{
parent[a] = parent[b];
size[a]+=size[b];
}
}
}
static boolean []visited = new boolean[1000];
public static void dfs(int vertex,ArrayList<ArrayList<Integer>>graph){
if(visited[vertex] == true){
return;
}
System.out.println(vertex);
for(int child : graph.get(vertex)){
// work to be done before entering the child
dfs(child,graph);
// work to be done after exitting the child
}
}
public static long solve(ArrayList<Long>list,long n,long idx,long sum,long itr){
if(idx==list.size()){
return Long.bitCount(n-sum) + itr;
}
return Math.min(solve(list,n,idx+1,sum,itr) , solve(list,n,idx+1,sum+list.get((int)idx),itr+1));
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
while(t-->0){
long n = scn.nextLong();
ArrayList<Long>factorial = new ArrayList<>();
long max = 1;
long temp = 2;
Long a = 1L;
for (int i = 1; i < 15; i++) {
a *= i;
factorial.add(a);
}
long ans = solve(factorial,n,0,0,0);
System.out.println(ans);
// System.out.println(ans);
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 17 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 3f7c68358ebe5c5e62b38c2849576d7e | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | /******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.util.*;
public class Main
{
public static boolean issorted(int []arr){
for(int i = 1;i<arr.length;i++){
if(arr[i]<arr[i-1]){
return false;
}
}
return true;
}
public static boolean ispalin(StringBuilder sb){
int i = 0;
int j = sb.length()-1;
while(i<=j){
if(sb.charAt(i) != sb.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
public static long sum(int []arr){
long sum = 0;
for(int i = 0;i<arr.length;i++){
sum+=arr[i];
}
return sum;
}
public static class pair{
long x;
long y;
pair(long x,long y){
this.x = x;
this.y = y;
}
}
public static void swap(int []arr,int i,int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static int gcd(int a, int b){
if (b == 0)
return a;
return gcd(b, a % b);
}
static int []parent = new int[1000];
static int []size = new int[1000];
public static void make(int v){
parent[v] = v;
size[v] = 1;
}
public static int find(int v){
if(parent[v]==v){
return v;
}
else{
return parent[v] = find(parent[v]);
}
}
public static void union(int a,int b){
a = find(a);
b = find(b);
if(a!=b){
if(size[a]>size[b]){
parent[b] = parent[a];
size[b]+=size[a];
}
else{
parent[a] = parent[b];
size[a]+=size[b];
}
}
}
static boolean []visited = new boolean[1000];
public static void dfs(int vertex,ArrayList<ArrayList<Integer>>graph){
if(visited[vertex] == true){
return;
}
System.out.println(vertex);
for(int child : graph.get(vertex)){
// work to be done before entering the child
dfs(child,graph);
// work to be done after exitting the child
}
}
public static long solve(ArrayList<Long>list,long n,long idx,long sum,long itr){
if(idx<list.size()){
return Math.min(solve(list,n,idx+1,sum,itr) , solve(list,n,idx+1,sum+list.get((int)idx),itr+1));
}
else{
return Long.bitCount(n-sum) + itr;
}
}
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
while(t-->0){
long n = scn.nextLong();
ArrayList<Long>factorial = new ArrayList<>();
long max = 1;
long temp = 2;
Long a = 1L;
for (int i = 1; i < 15; i++) {
a *= i;
factorial.add(a);
}
long ans = solve(factorial,n,0,0,0);
System.out.println(Math.min(Long.bitCount(n),ans));
// System.out.println(ans);
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 17 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | cbf139bdc69d90cb287166d37873d725 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
import static java.lang.System.*;
import static java.util.Arrays.*;
import static java.util.stream.IntStream.iterate;
public class Template {
private static final FastScanner scanner = new FastScanner();
private static void solve() {
long n = l();
List<Long> facts = new ArrayList<>();
long fact = 6, next = 4;
while (fact<=n) {
facts.add(fact);
fact*=(next++);
}
long ans = Long.MAX_VALUE;
for (long mask = 0; mask<1L<<facts.size(); mask++) {
long sum = n;
for (int i = 0; i<facts.size(); i++) {
if ((mask & (1L<<i)) != 0) sum-=facts.get(i);
}
ans = min(ans, Long.bitCount(mask)+Long.bitCount(sum));
}
out.println(ans);
}
public static void main(String[] args) {
int t = i();
while (t-->0) {
solve();
}
}
private static long fac(int n) {
long res = 1;
for (int i = 2; i<=n; i++) {
res*=i;
}
return res;
}
private static BigInteger factorial(int n) {
BigInteger res = BigInteger.valueOf(1);
for (int i = 2; i <= n; i++){
res = res.multiply(BigInteger.valueOf(i));
}
return res;
}
private static long l() {
return scanner.nextLong();
}
private static int i() {
return scanner.nextInt();
}
private static String s() {
return scanner.next();
}
private static void yes() {
out.println("YES");
}
private static void no() {
out.println("NO");
}
private static int toInt(char c) {
return Integer.parseInt(c+"");
}
private static void printArray(long[] a) {
StringBuilder builder = new StringBuilder();
for (long i : a)
builder.append(i).append(' ');
out.println(builder);
}
private static void printArray(int[] a) {
StringBuilder builder = new StringBuilder();
for (int i : a)
builder.append(i).append(' ');
out.println(builder);
}
private static int binPow(int a, int n) {
if (n == 0)
return 1;
if (n % 2 == 1)
return binPow(a, n-1) * a;
else {
int b = binPow(a, n/2);
return b * b;
}
}
private static boolean isPrime(long n) {
return iterate(2, i -> (long) i * i <= n, i -> i + 1).noneMatch(i -> n % i == 0);
}
private static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
private static void stableSort(int[] a) {
List<Integer> list = stream(a).boxed().sorted().toList();
setAll(a, list::get);
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long[] readLong(int n) {
long[] a = new long[n];
for (int i = 0; i<n; i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
static class SegmentTreeRMXQ {
static int getMid(int s, int e) {
return s + (e - s) / 2;
}
static int MaxUtil(int[] st, int ss, int se, int l, int r, int node) {
if (l <= ss && r >= se)
return st[node];
if (se < l || ss > r)
return -1;
int mid = getMid(ss, se);
return max(
MaxUtil(st, ss, mid, l, r,
2 * node + 1),
MaxUtil(st, mid + 1, se, l, r,
2 * node + 2));
}
static void updateValue(int[] arr, int[] st, int ss, int se, int index, int value, int node) {
if (index < ss || index > se) {
System.out.println("Invalid Input");
return;
}
if (ss == se) {
arr[index] = value;
st[node] = value;
} else {
int mid = getMid(ss, se);
if (index <= mid)
updateValue(arr, st, ss, mid,
index, value,
2 * node + 1);
else
updateValue(arr, st, mid + 1, se, index,
value, 2 * node + 2);
st[node] = max(st[2 * node + 1],
st[2 * node + 2]);
}
}
static int getMax(int[] st, int n, int l, int r) {
if (l < 0 || r > n - 1 || l > r) {
System.out.print("Invalid Input\n");
return -1;
}
return MaxUtil(st, 0, n - 1, l, r, 0);
}
static int constructSTUtil(int[] arr, int ss, int se, int[] st, int si) {
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
int mid = getMid(ss, se);
st[si] = max(
constructSTUtil(arr, ss, mid,
st, si * 2 + 1),
constructSTUtil(arr, mid + 1,
se, st,
si * 2 + 2));
return st[si];
}
static int[] constructST(int[] arr, int n) {
int x = (int)Math.ceil(Math.log(n) / Math.log(2));
int max_size = 2 * (int)Math.pow(2, x) - 1;
int[] st = new int[max_size];
constructSTUtil(arr, 0, n - 1, st, 0);
return st;
}
}
static class SegmentTreeRMNQ {
int[] st;
int minVal(int x, int y) {
return min(x, y);
}
int getMid(int s, int e) {
return s + (e - s) / 2;
}
int RMQUtil(int ss, int se, int qs, int qe, int index) {
if (qs <= ss && qe >= se)
return st[index];
if (se < qs || ss > qe)
return Integer.MAX_VALUE;
int mid = getMid(ss, se);
return minVal(RMQUtil(ss, mid, qs, qe, 2 * index + 1),
RMQUtil(mid + 1, se, qs, qe, 2 * index + 2));
}
int RMQ(int n, int qs, int qe) {
if (qs < 0 || qe > n - 1 || qs > qe) {
System.out.println("Invalid Input");
return -1;
}
return RMQUtil(0, n - 1, qs, qe, 0);
}
int constructSTUtil(int[] arr, int ss, int se, int si) {
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
int mid = getMid(ss, se);
st[si] = minVal(constructSTUtil(arr, ss, mid, si * 2 + 1),
constructSTUtil(arr, mid + 1, se, si * 2 + 2));
return st[si];
}
void constructST(int[] arr, int n) {
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
int max_size = 2 * (int) Math.pow(2, x) - 1;
st = new int[max_size]; // allocate memory
constructSTUtil(arr, 0, n - 1, 0);
}
}
static class SegmentTreeRSQ
{
int[] st; // The array that stores segment tree nodes
/* Constructor to construct segment tree from given array. This
constructor allocates memory for segment tree and calls
constructSTUtil() to fill the allocated memory */
SegmentTreeRSQ(int[] arr, int n)
{
// Allocate memory for segment tree
//Height of segment tree
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
//Maximum size of segment tree
int max_size = 2 * (int) Math.pow(2, x) - 1;
st = new int[max_size]; // Memory allocation
constructSTUtil(arr, 0, n - 1, 0);
}
// A utility function to get the middle index from corner indexes.
int getMid(int s, int e) {
return s + (e - s) / 2;
}
/* A recursive function to get the sum of values in given range
of the array. The following are parameters for this function.
st --> Pointer to segment tree
si --> Index of current node in the segment tree. Initially
0 is passed as root is always at index 0
ss & se --> Starting and ending indexes of the segment represented
by current node, i.e., st[si]
qs & qe --> Starting and ending indexes of query range */
int getSumUtil(int ss, int se, int qs, int qe, int si)
{
// If segment of this node is a part of given range, then return
// the sum of the segment
if (qs <= ss && qe >= se)
return st[si];
// If segment of this node is outside the given range
if (se < qs || ss > qe)
return 0;
// If a part of this segment overlaps with the given range
int mid = getMid(ss, se);
return getSumUtil(ss, mid, qs, qe, 2 * si + 1) +
getSumUtil(mid + 1, se, qs, qe, 2 * si + 2);
}
/* A recursive function to update the nodes which have the given
index in their range. The following are parameters
st, si, ss and se are same as getSumUtil()
i --> index of the element to be updated. This index is in
input array.
diff --> Value to be added to all nodes which have I in range */
void updateValueUtil(int ss, int se, int i, int diff, int si)
{
// Base Case: If the input index lies outside the range of
// this segment
if (i < ss || i > se)
return;
// If the input index is in range of this node, then update the
// value of the node and its children
st[si] = st[si] + diff;
if (se != ss) {
int mid = getMid(ss, se);
updateValueUtil(ss, mid, i, diff, 2 * si + 1);
updateValueUtil(mid + 1, se, i, diff, 2 * si + 2);
}
}
// The function to update a value in input array and segment tree.
// It uses updateValueUtil() to update the value in segment tree
void updateValue(int arr[], int n, int i, int new_val)
{
// Check for erroneous input index
if (i < 0 || i > n - 1) {
System.out.println("Invalid Input");
return;
}
// Get the difference between new value and old value
int diff = new_val - arr[i];
// Update the value in array
arr[i] = new_val;
// Update the values of nodes in segment tree
updateValueUtil(0, n - 1, i, diff, 0);
}
// Return sum of elements in range from index qs (query start) to
// qe (query end). It mainly uses getSumUtil()
int getSum(int n, int qs, int qe)
{
// Check for erroneous input values
if (qs < 0 || qe > n - 1 || qs > qe) {
System.out.println("Invalid Input");
return -1;
}
return getSumUtil(0, n - 1, qs, qe, 0);
}
// A recursive function that constructs Segment Tree for array[ss..se].
// si is index of current node in segment tree st
int constructSTUtil(int arr[], int ss, int se, int si)
{
// If there is one element in array, store it in current node of
// segment tree and return
if (ss == se) {
st[si] = arr[ss];
return arr[ss];
}
// If there are more than one elements, then recur for left and
// right subtrees and store the sum of values in this node
int mid = getMid(ss, se);
st[si] = constructSTUtil(arr, ss, mid, si * 2 + 1) +
constructSTUtil(arr, mid + 1, se, si * 2 + 2);
return st[si];
}
}
} | Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 17 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | e7339b8fef40ba766805d8efcdee6e0a | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int tc = 0; tc < t; ++tc) {
long n = sc.nextLong();
System.out.println(solve(n));
}
sc.close();
}
static int solve(long n) {
List<Long> factorials = new ArrayList<>();
factorials.add(1L);
while (true) {
long next = factorials.get(factorials.size() - 1) * factorials.size();
if (next > n) {
break;
}
factorials.add(next);
}
return IntStream.range(0, 1 << factorials.size())
.map(
mask -> {
long rest =
n
- IntStream.range(0, factorials.size())
.filter(i -> (mask & (1 << i)) != 0)
.mapToLong(factorials::get)
.sum();
return (rest < 0)
? Integer.MAX_VALUE
: (Integer.bitCount(mask) + Long.bitCount(rest));
})
.min()
.getAsInt();
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 17 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | b4d87453dbf16d90f557e68022c82aa6 | train_110.jsonl | 1646408100 | A number is called powerful if it is a power of two or a factorial. In other words, the number $$$m$$$ is powerful if there exists a non-negative integer $$$d$$$ such that $$$m=2^d$$$ or $$$m=d!$$$, where $$$d!=1\cdot 2\cdot \ldots \cdot d$$$ (in particular, $$$0! = 1$$$). For example $$$1$$$, $$$4$$$, and $$$6$$$ are powerful numbers, because $$$1=1!$$$, $$$4=2^2$$$, and $$$6=3!$$$ but $$$7$$$, $$$10$$$, or $$$18$$$ are not.You are given a positive integer $$$n$$$. Find the minimum number $$$k$$$ such that $$$n$$$ can be represented as the sum of $$$k$$$ distinct powerful numbers, or say that there is no such $$$k$$$. | 256 megabytes |
import java.util.*;
import java.io.*;
public class B {
static int countSetBits(long n){
int count = 0;
while(n>0){
n = n&(n-1);
count++;
}
return count;
}
static long fact(long n){
long fact = 1;
for(long i = 1;i<=n;i++){
fact = fact * i;
}
return fact;
}
public static String pad(String s, int n){
return "0".repeat(Math.max(0, n - s.length())) + s;
}
public static void main(String[] args) throws IOException {
Soumit sc = new Soumit();
long[] fact = new long[15];
for(int i=1;i<=15;i++){
fact[i - 1] = fact(i);
}
List<Long> list = new ArrayList<>();
int lim = (1 << 15);
for(int i=0;i<lim;i++){
String bin = Integer.toBinaryString(i);
bin = pad(bin, 15);
long sum = 0;
for(int j=0;j<15;j++){
if(bin.charAt(j)=='1')
sum += fact[j];
}
list.add(sum);
}
int tc = sc.nextInt();
StringBuilder sb = new StringBuilder();
while (tc-->0){
long n = sc.nextLong();
int min = 100;
for(int i=0;i<list.size();i++){
if(list.get(i) > n)
continue;
long cur = n - list.get(i);
int count = countSetBits(i) + countSetBits(cur);
min = Math.min(min, count);
}
sb.append(min).append("\n");
}
System.out.println(sb);
sc.close();
}
static class Soumit {
final private int BUFFER_SIZE = 1 << 18;
final private DataInputStream din;
final private byte[] buffer;
private PrintWriter pw;
private int bufferPointer, bytesRead;
StringTokenizer st;
public Soumit() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Soumit(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public void streamOutput(String file) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
}
public void println(String a) {
pw.println(a);
}
public void print(String a) {
pw.print(a);
}
public String readLine() throws IOException {
byte[] buf = new byte[3000064]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public void sort(int[] arr) {
ArrayList<Integer> arlist = new ArrayList<>();
for (int i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public void sort(long[] arr) {
ArrayList<Long> arlist = new ArrayList<>();
for (long i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
/*if (din == null)
return;*/
if (din != null) din.close();
if (pw != null) pw.close();
}
}
}
| Java | ["4\n\n7\n\n11\n\n240\n\n17179869184"] | 3 seconds | ["2\n3\n4\n1"] | NoteIn the first test case, $$$7$$$ can be represented as $$$7=1+6$$$, where $$$1$$$ and $$$6$$$ are powerful numbers. Because $$$7$$$ is not a powerful number, we know that the minimum possible value of $$$k$$$ in this case is $$$k=2$$$.In the second test case, a possible way to represent $$$11$$$ as the sum of three powerful numbers is $$$11=1+4+6$$$. We can show that there is no way to represent $$$11$$$ as the sum of two or less powerful numbers. In the third test case, $$$240$$$ can be represented as $$$240=24+32+64+120$$$. Observe that $$$240=120+120$$$ is not a valid representation, because the powerful numbers have to be distinct. In the fourth test case, $$$17179869184=2^{34}$$$, so $$$17179869184$$$ is a powerful number and the minimum $$$k$$$ in this case is $$$k=1$$$. | Java 17 | standard input | [
"bitmasks",
"brute force",
"constructive algorithms",
"dp",
"math"
] | ff0b041d54755984df3706aae78d8ff2 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. A test case consists of only one line, containing one integer $$$n$$$ ($$$1\le n\le 10^{12}$$$). | 1,500 | For each test case print the answer on a separate line. If $$$n$$$ can not be represented as the sum of distinct powerful numbers, print $$$-1$$$. Otherwise, print a single positive integer — the minimum possible value of $$$k$$$. | standard output | |
PASSED | 1c4dab41c8459a0435b774ef0290e77d | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | // package c1646;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
//
// Codeforces Round #774 (Div. 2) 2022-03-04 07:35
// D. Weight the Tree
// https://codeforces.com/contest/1646/problem/D
// time limit per test 2 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// You are given a tree of n vertices numbered from 1 to n. A tree is a connected undirected graph
// without cycles.
//
// For each i=1,2, ..., n, let w_i be the weight of the i-th vertex. A vertex is called if its
// weight is equal to the sum of the weights of all its neighbors.
//
// Initially, the weights of all nodes are unassigned. Assign positive integer weights to each
// vertex of the tree, such that the number of good vertices in the tree is maximized. If there are
// multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in
// the tree.
//
// Input
//
// The first line contains one integer n (2<= n<= 2* 10^5) -- the number of vertices in the tree.
//
// Then, n-1 lines follow. Each of them contains two integers u and v (1<= u,v<= n) denoting an edge
// between vertices u and v. It is guaranteed that the edges form a tree.
//
// Output
//
// In the first line print two integers -- the maximum number of good vertices and the minimum
// possible sum of weights for that maximum.
//
// In the second line print n integers w_1, w_2, ..., w_n (1<= w_i<= 10^9) -- the corresponding
// weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying
// these constraints.
//
// If there are multiple optimal solutions, you may print any.
//
// Example
/*
input:
4
1 2
2 3
2 4
output:
3 4
1 1 1 1
input:
3
1 2
1 3
output:
2 3
1 1 1
input:
2
1 2
output:
2 2
1 1
input:
9
3 4
7 6
2 1
8 3
5 6
1 8
8 6
9 6
output:
6 11
1 1 1 1 1 1 1 3 1
*/
// Note
//
// This is the tree for the first test case:
// https://espresso.codeforces.com/fcb7a0361f49ebc6c1ebe8ab10feeb28965d4123.png In this case, if you
// assign a weight of 1 to each vertex, then the good vertices (which are painted black) are 1, 3
// and 4. It impossible to assign weights so that all vertices are good vertices. The minimum sum of
// weights in this case is 1+1+1+1=4, and it is impossible to have a lower sum because the weights
// have to be positive integers.
//
// This is the tree for the second test case:
// https://espresso.codeforces.com/1512e4afbd87b887047491bcc8949e20f8ab5841.png In this case, if you
// assign a weight of 1 to each vertex, then the good vertices (which are painted black) are 2 and
// 3. It can be proven that this is an optimal assignment.
//
public class C1646D {
static final int MOD = 998244353;
static final Random RAND = new Random();
static Result solve(int[][] edges) {
int n = edges.length + 1;
if (n == 2) {
return new Result(2, 2, new int[] {1,1});
}
List<Set<Integer>> nbs = new ArrayList<>();
for (int i = 0; i < n; i++) {
nbs.add(new HashSet<>());
}
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
nbs.get(u).add(v);
nbs.get(v).add(u);
}
int[] weight = new int[n];
// dp[i][0]: max count of good node if i is good
// dp[i][1]: min sum if i is good
// dp[i][2]: max count of good node if i is bad
// dp[i][3]: min sum if i is bad
int[][] dp = new int[n][4];
dp1(0, -1, dp, weight, nbs);
dp2(0, -1, false, dp, weight, nbs);
if(dp[0][2] > dp[0][0] || (dp[0][2] == dp[0][0] && dp[0][3] <= dp[0][1])) {
return new Result(dp[0][2], dp[0][3], weight);
} else {
return new Result(dp[0][0], dp[0][1], weight);
}
}
public static void dp1(int i, int prev, int[][] dp, int[] weight, List<Set<Integer>> nbs) {
if (nbs.get(i).size() == 1 && nbs.get(i).contains(prev)) {
dp[i] = new int[]{1, 1, 0, 1};
return;
}
int[] res = new int[4];
res[0] = 1;
res[1] = nbs.get(i).size();
res[3] = 1;
for (int next: nbs.get(i)) {
if(next == prev) {
continue;
}
dp1(next, i, dp, weight, nbs);
int[] t = dp[next];
res[0] += t[2];
res[1] += t[3];
if (t[0] < t[2]) {
res[2] += t[2];
res[3] += t[3];
} else if (t[0] > t[2]){
res[2] += t[0];
res[3] += t[1];
} else {
res[2] += t[0];
res[3] += Math.min(t[1], t[3]);
}
}
dp[i] = res;
}
public static void dp2(int i, int prev, boolean isPrevGood,
int[][] dp, int[] weight, List<Set<Integer>> nbs) {
int[] t = dp[i];
boolean isGood;
if (isPrevGood || t[2] > t[0] || (t[2] == t[0] && t[3] <= t[1])) {
weight[i] = 1;
isGood = false;
} else {
weight[i] = nbs.get(i).size();
isGood = true;
}
for (int next: nbs.get(i)) {
if(next == prev) {
continue;
}
dp2(next, i, isGood, dp, weight, nbs);
}
}
static class Result {
int numGood = 0;
long sum = 0;
int[] weights;
public Result(int n) {
weights = new int[n];
}
public Result(int good, long sum, int[] wt) {
this.numGood = good;
this.sum = sum;
this.weights = wt;
}
@Override
public
String toString() {
return String.format("%d:%d:%s", numGood, sum, Arrays.toString(weights).replace(" ", ""));
}
}
static List<List<Integer>> getNeighborsList(int[][] edges) {
int n = edges.length + 1;
List<List<Integer>> eas = new ArrayList<>();
for (int i = 0; i < n; i++) {
eas.add(new ArrayList<>());
}
for (int[] edge : edges) {
int u = edge[0];
int v = edge[1];
eas.get(u).add(v);
eas.get(v).add(u);
}
return eas;
}
public static String traceListInt(List<Integer> values) {
StringBuilder sb = new StringBuilder();
sb.append('[');
int n = values.size();
for (int i = 0; i < n; i++) {
if (i < 16 || i >= n - 16) {
if (i > 0) {
sb.append(',');
}
sb.append(values.get(i));
}
if (n > 32 && i == 16) {
sb.append(",...");
}
}
sb.append(']');
return sb.toString();
}
public static String traceSimple(int[][] points) {
StringBuilder sb = new StringBuilder();
sb.append('{');
int h = 10;
int m = points.length;
for (int i = 0; i < m; i++) {
if (m > (h << 1)) {
if (i == h) {
sb.append(",...");
}
if (i >= h && i < m - h) {
continue;
}
}
if (i > 0) {
sb.append(',');
}
sb.append('{');
int n = points[i].length;
for (int j = 0; j < n; j++) {
// If more than 32 cols, we trace the first 16 and last 16
if (n > (h << 1)) {
if (j == h) {
sb.append(",...");
}
if (j >= h && j < n - h) {
continue;
}
}
if (j > 0) {
sb.append(',');
}
sb.append(points[i][j]);
}
sb.append('}');
}
sb.append('}');
return sb.toString();
}
static void verify(int[][] edges, Result res) {
int n = edges.length + 1;
List<List<Integer>> nbs = getNeighborsList(edges);
int numGood = 0;
long total = 0;
for (int i = 0; i < n; i++) {
myAssert(res.weights[i] >= 1);
total += res.weights[i];
int sum = 0;
for (int v : nbs.get(i)) {
sum += res.weights[v];
}
if (res.weights[i] == sum) {
numGood++;
}
}
myAssert(numGood == res.numGood);
myAssert(total == res.sum);
}
static Result solveNaive(int[][] edges) {
int n = edges.length + 1;
if (n == 2) {
return new Result(2,2,new int[] {1,1});
}
List<List<Integer>> nbs = getNeighborsList(edges);
int[] wt = new int[n];
int numOkmax = 0;
int sumMin = Integer.MAX_VALUE;
int[] wtMin = new int[n];
for (int i = 0; i < (1 << n); i++) {
Arrays.fill(wt, 1);
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) != 0) {
wt[j] = nbs.get(j).size();
}
}
int numOk = 0;
int sum = 0;
for (int j = 0; j < n; j++) {
List<Integer> nb = nbs.get(j);
sum += wt[j];
int add = 0;
for (int v : nb) {
add += wt[v];
}
if (wt[j] == add) {
numOk++;
}
}
if (numOk > numOkmax || (numOk == numOkmax && sum < sumMin)) {
numOkmax = numOk;
sumMin = sum;
System.arraycopy(wt, 0, wtMin, 0, n);
}
}
return new Result(numOkmax, sumMin, wtMin);
}
static boolean test = false;
static void doTest() {
if (!test) {
return;
}
long t0 = System.currentTimeMillis();
int n = 12;
for (int t = 0; t < 100; t++) {
int[][] edges = generateEdges(n);
// edges = new int[][] {{0,3},{9,0},{6,3},{5,3},{2,5},{7,9},{8,7},{4,7},{1,6}};
// edges = new int[][] {{0,3},{0,2},{0,8},{5,3},{2,6},{6,9},{6,4},{1,9},{4,7}};
// edges = new int[][] {{0,8},{6,8},{1,8},{5,6},{9,0},{7,5},{4,5},{3,4},{2,7}};
// edges = new int[][] {{16,11},{3,11},{9,3},{0,3},{13,0},{14,13},{12,13},{4,9},
// {5,4},{1,14},{17,1},{8,17},{2,12},{15,12},{10,9},{7,10},{6,4}};
// edges = new int[][] {{8,4},{12,8},{6,4},{5,4},{16,8},{11,16},{2,6},{9,11},{17,5},
// {13,11},{3,9},{15,3},{14,12},{0,12},{1,9},{7,13},{10,6}};
System.out.println(traceSimple(edges));
// int[][] edges = new int[][] {{0,1},{1,2},{2,3},{3,4}};
// edges = new int[][] {{0,2},{1,2},{2,3},{3,4},{4,5},{4,6}};
Result ans = solve(edges);
verify(edges, ans);
Result exp = solveNaive(edges);
System.out.format("ans:%s\n", ans);
System.out.format("exp:%s\n", exp);
myAssert(ans.numGood == exp.numGood);
myAssert(ans.sum == exp.sum);
}
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
static void test(int[][] edges) {
Result res = solve(edges);
output(res);
verify(edges, res);
}
public static int[][] generateEdges(int n) {
int[][] edges = new int[n-1][2];
if (n == 1) {
return edges;
}
List<Integer> used = new ArrayList<>();
List<Integer> avai = new ArrayList<>();
Random rand = new Random();
int i0 = rand.nextInt(n);
used.add(i0);
for (int i = 0; i < n; i++) {
if (i != i0) {
avai.add(i);
}
}
int idx = 0;
while (!avai.isEmpty()) {
int v = avai.remove(rand.nextInt(avai.size()));
int w = used.get(rand.nextInt(used.size()));
edges[idx][0] = v;
edges[idx][1] = w;
idx++;
used.add(v);
}
return edges;
}
public static void main(String[] args) {
doTest();
MyScanner in = new MyScanner();
int n = in.nextInt();
int[][] edges = new int[n-1][2];
for (int i = 0; i < n - 1; i++) {
edges[i][0] = in.nextInt() - 1;
edges[i][1] = in.nextInt() - 1;
}
Result res = solve(edges);
output(res);
}
static void output(Result res) {
System.out.format("%d %d\n", res.numGood, res.sum);
StringBuilder sb = new StringBuilder();
for (int v : res.weights) {
sb.append(v);
sb.append(' ');
if (sb.length() > 500) {
System.out.print(sb.toString());
sb.setLength(0);
}
}
System.out.println(sb.toString());
}
static void myAssert(boolean cond) {
if (!cond) {
throw new RuntimeException("Unexpected");
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
String cname = MethodHandles.lookup().lookupClass().getCanonicalName();
cname = cname.lastIndexOf('.') > 0 ? cname.substring(0, cname.lastIndexOf('.')) : cname;
final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
br = new BufferedReader(new InputStreamReader(fin.exists()
? new FileInputStream(fin) : System.in));
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String next() {
try {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | c4ea5a85d8de5c064c4c06f625518f39 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.lang.Math;
import java.nio.BufferOverflowException;
import java.util.*;
import java.io.*;
import java.lang.Math;
public final class code {
static int globalCnt = 0;
static int loss = 0;
/*
* static class sortCond implements Comparator<Pair<Integer, Integer>> {
*
* @Override
* public int compare(Pair<Integer, Integer> obj, Pair<Integer, Integer> obj1) {
* if (obj.getValue() < obj1.getValue()) {
* return -1;
* } else {
* return 1;
* }
* }
* }
*/
static class Pair {
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
int getKey() {
return this.a;
}
int getValue() {
return this.b;
}
}
/*
* static class Pair<f, s> {
* f a;
* s b;
*
* Pair(f a, s b) {
* this.a = a;
* this.b = b;
* }
*
* f getKey() {
* return this.a;
* }
*
* s getValue() {
* return this.b;
* }
*
* }
*/
interface modOperations {
long mod(long a, long b, long mod);
}
static long findBinaryExponentian(long a, long pow, long mod) {
if (pow == 1) {
return a;
} else if (pow == 0) {
return 1;
} else {
long retVal = findBinaryExponentian(a, (int) pow / 2, mod);
return modMul.mod(modMul.mod(retVal, retVal, mod), (pow % 2 == 0) ? 1 : a, mod);
}
}
static long findPow(long a, int b) {
if (b == 1) {
return a;
} else if (b == 0) {
return 1L;
} else {
long res = findPow(a, (int) b / 2);
return res * res * (b % 2 == 1 ? a : 1);
}
}
static int bleft(int ele, ArrayList<Integer> sortedArr) {
int l = 0;
int h = sortedArr.size() - 1;
int ans = -1;
while (l <= h) {
int mid = l + (int) (h - l) / 2;
if (sortedArr.get(mid) < ele) {
l = mid + 1;
} else if (sortedArr.get(mid) >= ele) {
ans = mid;
h = mid - 1;
}
}
return ans;
}
static long gcd(long a, long b) {
long div = b;
long rem = a % b;
while (rem != 0) {
long temp = rem;
rem = div % rem;
div = temp;
}
return div;
}
static int log(long no) {
int i = 0;
while ((1 << i) <= no) {
i += 1;
}
return i - 1;
}
static modOperations modAdd = (long a, long b, long mod) -> {
return (a % mod + b % mod) % mod;
};
static modOperations modSub = (long a, long b, long mod) -> {
return (a % mod - b % mod + mod) % mod;
};
static modOperations modMul = (long a, long b, long mod) -> {
return (a % mod * b % mod) % mod;
};
static modOperations modDiv = (long a, long b, long mod) -> {
return modMul.mod(a, findBinaryExponentian(b, mod - 1, mod), mod);
};
static ArrayList<Integer> primeList(int MAXI) {
int[] prime = new int[MAXI + 1];
ArrayList<Integer> obj = new ArrayList<Integer>();
for (int i = 2; i <= (int) Math.sqrt(MAXI) + 1; i++) {
if (prime[i] == 0) {
obj.add(i);
for (int j = i * i; j <= MAXI; j += i) {
prime[j] = 1;
}
}
}
for (int i = (int) Math.sqrt(MAXI) + 1; i <= MAXI; i++) {
if (prime[i] == 0) {
obj.add(i);
}
}
return obj;
}
static int arrSum(int[] arr) {
int tot = 0;
for (int i = 0; i < arr.length; i++) {
tot += arr[i];
}
return tot;
}
static void dptraversal(ArrayList<ArrayList<Integer>> tree, Pair[] good, Pair[] nGood, int root, int par) {
int ninc = 0, nchild = 0, inc = 0, child = 0;
for (int i = 0; i < tree.get(root).size(); i++) {
if (tree.get(root).get(i) != par) {
dptraversal(tree, good, nGood, tree.get(root).get(i), root);
inc += nGood[tree.get(root).get(i)].getValue();
child += nGood[tree.get(root).get(i)].getKey();
if (nGood[tree.get(root).get(i)].getKey() > good[tree.get(root).get(i)].getKey()) {
nchild += nGood[tree.get(root).get(i)].getKey();
ninc += nGood[tree.get(root).get(i)].getValue();
} else if (nGood[tree.get(root).get(i)].getKey() < good[tree.get(root).get(i)].getKey()){
nchild += good[tree.get(root).get(i)].getKey();
ninc += good[tree.get(root).get(i)].getValue();
}else{
if(nGood[tree.get(root).get(i)].getValue() <= good[tree.get(root).get(i)].getValue()){
nchild += nGood[tree.get(root).get(i)].getKey();
ninc += nGood[tree.get(root).get(i)].getValue();
}else{
nchild += good[tree.get(root).get(i)].getKey();
ninc += good[tree.get(root).get(i)].getValue();
}
}
}
}
good[root] = new Pair(child + 1, inc + tree.get(root).size() + (par == -1 ? 0 : 1));
nGood[root] = new Pair(nchild, ninc + 1);
}
static void assignment(ArrayList<ArrayList<Integer>> tree, boolean isBad, int g[], Pair[] good, Pair[] nGood,
int root, int par) {
boolean isSat = true;
if (isBad) {
isSat = false;
} else if (good[root].getKey() < nGood[root].getKey()) {
isSat = false;
} else if (good[root].getKey() == nGood[root].getKey() && good[root].getValue() >= nGood[root].getValue()) {
isSat = false;
} else {
g[root] = 1;
}
for (int i = 0; i < tree.get(root).size(); i++) {
if (tree.get(root).get(i) != par) {
assignment(tree, isSat, g, good, nGood, tree.get(root).get(i), root);
}
}
}
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine()), i, u, v, cnt = 0, sum = 0;
ArrayList<ArrayList<Integer>> tree = new ArrayList<>();
for (i = 0; i < n; i++) {
tree.add(new ArrayList<>());
}
for (i = 0; i < n - 1; i++) {
String a[] = br.readLine().split(" ");
u = Integer.parseInt(a[0]);
v = Integer.parseInt(a[1]);
tree.get(u - 1).add(v - 1);
tree.get(v - 1).add(u - 1);
}
if (n == 2) {
System.out.println(2 + " " + 2);
System.out.println(1 + " " + 1);
} else {
Pair[] good = new Pair[n];
Pair[] nGood = new Pair[n];
int[] g = new int[n];
int aa[] = new int[n];
dptraversal(tree, good, nGood, 0, -1);
assignment(tree, false, g, good, nGood, 0, -1);
/*
* for (i = 0; i < n; i++) {
* System.out.println(i);
* System.out.println(good[i].getKey() + " " + good[i].getValue());
* System.out.println(nGood[i].getKey() + " " + nGood[i].getValue());
* }
*/
for (i = 0; i < n; i++) {
if (g[i] == 1) {
cnt++;
sum += tree.get(i).size();
aa[i] = tree.get(i).size();
} else {
sum += 1;
aa[i] = 1;
}
}
System.out.println(cnt + " " + sum);
for (i = 0; i < n; i++) {
System.out.print(aa[i] + " ");
}
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | f348377e3d44303d81737836432729b2 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | // package cp_stuff.Codeforces_Problems;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
/**
* yo
*/
public class yo {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int N = sc.nextInt();
Node nodes[] = new Node[N];
DP dp[][] = new DP[N][2];
for(int i=0;i<N;++i) {
nodes[i] = new Node(i);
dp[i][0] = new DP(0, 0);
dp[i][1] = new DP(0, 0);
}
for(int i=0;i<(N - 1);++i) {
int u = sc.nextInt();
int v = sc.nextInt();
// System.out.println("Edge: " + u + "," + v);
u--; v--;
nodes[u].adj.add(nodes[v]);
nodes[v].adj.add(nodes[u]);
}
// sc.close();
//TODO: n = 2 edge case
if(N == 2) {
out.println(2 + " " + 2);
out.println(1 + " " + 1);
out.close();
return;
}
DFS1(nodes[0], null, dp);
int type = getOptimalType(nodes[0], dp);
DFS2(nodes[0], null, dp, type);
out.println(dp[nodes[0].value][type].maxValue + " " + dp[nodes[0].value][type].minSum);
for(int i=0;i<N;++i) {
out.print(nodes[i].weight + " ");
}
out.println();
out.close();
}
static void getOptimal0(Node root, Node child, DP dp[][]) {
int optimalValue;
int optimalSum;
if(dp[child.value][0].maxValue == dp[child.value][1].maxValue) {
optimalSum = Math.min(dp[child.value][0].minSum, dp[child.value][1].minSum);
}
else if(dp[child.value][0].maxValue > dp[child.value][1].maxValue) {
optimalSum = dp[child.value][0].minSum;
}
else {
optimalSum = dp[child.value][1].minSum;
}
optimalValue = Math.max(dp[child.value][0].maxValue, dp[child.value][1].maxValue);
dp[root.value][0].minSum += optimalSum;
dp[root.value][0].maxValue += optimalValue;
}
static void getOptimal1(Node root, Node child, DP dp[][]) {
dp[root.value][1].minSum += dp[child.value][0].minSum;
dp[root.value][1].maxValue += dp[child.value][0].maxValue;
}
static int getOptimalType(Node node, DP dp[][]) {
if(dp[node.value][0].maxValue == dp[node.value][1].maxValue) {
if(dp[node.value][0].minSum > dp[node.value][1].minSum) return 1;
else return 0;
}
else if(dp[node.value][0].maxValue > dp[node.value][1].maxValue) {
return 0;
}
return 1;
}
static void DFS1(Node root, Node parent, DP dp[][]) {
// System.out.println("root: " + root.value);
for(Node child: root.adj) {
if((parent == null) || (child.value != parent.value)) {
DFS1(child, root, dp);
getOptimal0(root, child, dp);
getOptimal1(root, child, dp);
}
}
dp[root.value][0].minSum++;
dp[root.value][1].maxValue++;
dp[root.value][1].minSum += root.adj.size();
// System.out.println("root: " + root.value + "take => " + dp[root.value][1].maxValue + "skip => " + dp[root.value][0].maxValue);
}
//build the answer
static void DFS2(Node root, Node parent, DP dp[][], int type) {;
if(type == 1) root.weight += root.adj.size();
else root.weight++;
for(Node child: root.adj) {
if((parent == null) || (child.value != parent.value)) {
if(type == 1) {
DFS2(child, root, dp, 0);
}
else {
int childType = getOptimalType(child, dp);
DFS2(child, root, dp, childType);
}
}
}
}
static class Node {
int value;
int weight;
List<Node> adj = new ArrayList<>();
public Node(int value) {
this.value = value;
weight = 0;
}
}
static class DP {
int maxValue;
int minSum;
public DP(int maxValue, int minSum) {
this.maxValue = maxValue;
this.minSum = minSum;
}
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 3967e7e18faf849c5c567ea9d3230f8f | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | // package cp_stuff.Codeforces_Problems;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
// import java.io.PrintWriter;
/**
* yo
*/
public class yo {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int N = sc.nextInt();
Node nodes[] = new Node[N];
DP dp[][] = new DP[N][2];
for(int i=0;i<N;++i) {
nodes[i] = new Node(i);
dp[i][0] = new DP(0, 0);
dp[i][1] = new DP(0, 0);
}
for(int i=0;i<(N - 1);++i) {
int u = sc.nextInt();
int v = sc.nextInt();
// System.out.println("Edge: " + u + "," + v);
u--; v--;
nodes[u].adj.add(nodes[v]);
nodes[v].adj.add(nodes[u]);
}
// sc.close();
//TODO: n = 2 edge case
if(N == 2) {
System.out.println(2 + " " + 2);
System.out.println(1 + " " + 1);
return;
}
DFS1(nodes[0], null, dp);
int type = getOptimalType(nodes[0], dp);
DFS2(nodes[0], null, dp, type);
System.out.println(dp[nodes[0].value][type].maxValue + " " + dp[nodes[0].value][type].minSum);
for(int i=0;i<N;++i) {
System.out.print(nodes[i].weight + " ");
}
System.out.println();
}
static void getOptimal0(Node root, Node child, DP dp[][]) {
int optimalValue;
int optimalSum;
if(dp[child.value][0].maxValue == dp[child.value][1].maxValue) {
optimalSum = Math.min(dp[child.value][0].minSum, dp[child.value][1].minSum);
}
else if(dp[child.value][0].maxValue > dp[child.value][1].maxValue) {
optimalSum = dp[child.value][0].minSum;
}
else {
optimalSum = dp[child.value][1].minSum;
}
optimalValue = Math.max(dp[child.value][0].maxValue, dp[child.value][1].maxValue);
dp[root.value][0].minSum += optimalSum;
dp[root.value][0].maxValue += optimalValue;
}
static void getOptimal1(Node root, Node child, DP dp[][]) {
dp[root.value][1].minSum += dp[child.value][0].minSum;
dp[root.value][1].maxValue += dp[child.value][0].maxValue;
}
static int getOptimalType(Node node, DP dp[][]) {
if(dp[node.value][0].maxValue == dp[node.value][1].maxValue) {
if(dp[node.value][0].minSum > dp[node.value][1].minSum) return 1;
else return 0;
}
else if(dp[node.value][0].maxValue > dp[node.value][1].maxValue) {
return 0;
}
return 1;
}
static void DFS1(Node root, Node parent, DP dp[][]) {
// System.out.println("root: " + root.value);
for(Node child: root.adj) {
if((parent == null) || (child.value != parent.value)) {
DFS1(child, root, dp);
getOptimal0(root, child, dp);
getOptimal1(root, child, dp);
}
}
dp[root.value][0].minSum++;
dp[root.value][1].maxValue++;
dp[root.value][1].minSum += root.adj.size();
// System.out.println("root: " + root.value + "take => " + dp[root.value][1].maxValue + "skip => " + dp[root.value][0].maxValue);
}
//build the answer
static void DFS2(Node root, Node parent, DP dp[][], int type) {;
if(type == 1) root.weight += root.adj.size();
else root.weight++;
for(Node child: root.adj) {
if((parent == null) || (child.value != parent.value)) {
if(type == 1) {
DFS2(child, root, dp, 0);
}
else {
int childType = getOptimalType(child, dp);
DFS2(child, root, dp, childType);
}
}
}
}
static class Node {
int value;
int weight;
List<Node> adj = new ArrayList<>();
public Node(int value) {
this.value = value;
weight = 0;
}
}
static class DP {
int maxValue;
int minSum;
public DP(int maxValue, int minSum) {
this.maxValue = maxValue;
this.minSum = minSum;
}
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 4694528be024ca547f19bd9ffb5ae8e9 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DWeightTheTree solver = new DWeightTheTree();
solver.solve(1, in, out);
out.close();
}
static class DWeightTheTree {
int[][][] dp;
int[][] g;
int[] ans;
int n;
int m;
int[] from;
int[] to;
int[] d;
public void solve(int testNumber, InputReader in, OutputWriter out) {
g = makeGraph(in);
dp = new int[n][2][2];
// dp[i][0]= max good vertices in subtree of i such that i is not good with min sum
// dp[i][1]= max good vertices in subtree of i such that i is good with min sum
dfs(0, -1);
ans = new int[n];
int sum = 0;
if (dp[0][0][0] == dp[0][1][0]) {
if (dp[0][0][1] < dp[0][1][1]) {
dfs1(0, -1, 0);
} else {
dfs1(0, -1, 1);
}
} else if (dp[0][0][0] > dp[0][1][0]) {
dfs1(0, -1, 0);
} else {
dfs1(0, -1, 1);
}
int tot = 0;
for (int i = 0; i < n; i++) {
int val = 0;
for (int a : g[i]) {
val += ans[a];
}
if (val == ans[i]) {
tot++;
}
sum += ans[i];
}
out.println(tot, sum);
out.println(ans);
}
void dfs1(int nn, int pp, int c) {
if (c == 0) {
ans[nn] = 1;
} else {
ans[nn] = d[nn];
}
for (int a : g[nn]) {
if (a == pp) continue;
if (c == 1) {
dfs1(a, nn, 0);
} else {
if (dp[a][0][0] == dp[a][1][0]) {
if (dp[a][0][1] < dp[a][1][1]) {
dfs1(a, nn, 0);
} else {
dfs1(a, nn, 1);
}
} else if (dp[a][0][0] > dp[a][1][0]) {
dfs1(a, nn, 0);
} else {
dfs1(a, nn, 1);
}
}
}
}
void dfs(int nn, int pp) {
dp[nn][0][1] = 1;
dp[nn][1][1] = d[nn];
dp[nn][1][0] = 1;
for (int a : g[nn]) {
if (a == pp) continue;
dfs(a, nn);
dp[nn][1][0] += dp[a][0][0];
dp[nn][1][1] += dp[a][0][1];
dp[nn][0][0] += Math.max(dp[a][0][0], dp[a][1][0]);
if (dp[a][0][0] == dp[a][1][0]) {
dp[nn][0][1] += Math.min(dp[a][0][1], dp[a][1][1]);
} else if (dp[a][0][0] > dp[a][1][0]) {
dp[nn][0][1] += dp[a][0][1];
} else {
dp[nn][0][1] += dp[a][1][1];
}
}
}
int[][] makeGraph(InputReader in) {
n = in.nextInt();
d = new int[n];
m = n - 1;
from = new int[m];
to = new int[m];
for (int i = 0; i < m; i++) {
int a = in.nextInt() - 1, b = in.nextInt() - 1;
from[i] = a;
to[i] = b;
d[a]++;
d[b]++;
}
return makeGraph(n, m);
}
int[][] makeGraph(int N, int M) {
int[][] G = new int[N][];
int[] p = new int[N];
for (int i = 0; i < M; i++) {
p[from[i]]++;
p[to[i]]++;
}
for (int i = 0; i < N; i++) G[i] = new int[p[i]];
for (int i = 0; i < M; i++) {
G[from[i]][--p[from[i]]] = to[i];
G[to[i]][--p[to[i]]] = from[i];
}
return G;
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void println(int[] array) {
print(array);
writer.println();
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 197989339bac64c3308d73700666f8ab | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static AReader scan = new AReader();
static int N = 200010;
static int M = N * 2;
static int[] h = new int[N];
static int[] e = new int[M];
static int[] ne = new int[M];
static int idx = 0;
static int[] ans = new int[N];
static int[] d = new int[N];
// 0不是好节点 1是好节点
static int[][] dp = new int[N][2];
// 统计节点权值
static int[][] f = new int[N][2];
static boolean[] choose = new boolean[N];
static void add(int a,int b){
e[idx] = b;ne[idx] = h[a];h[a] = idx++;d[b]++;
}
static void dfs(int u,int fa){
dp[u][0] = 0;f[u][0] = 1;
dp[u][1] = 1;f[u][1] = d[u];
for(int i = h[u];i!=-1;i=ne[i]){
int j = e[i];
if(j == fa) continue;
dfs(j,u);
if(dp[j][0] > dp[j][1]){
dp[u][0] += dp[j][0];
f[u][0] += f[j][0];
}else if(dp[j][0] < dp[j][1]){
dp[u][0] += dp[j][1];
f[u][0] += f[j][1];
}else{
dp[u][0] += dp[j][0];
f[u][0] += Math.min(f[j][0],f[j][1]);
}
dp[u][1] += dp[j][0];
f[u][1] += f[j][0];
}
}
static void DFS(int u,int fa){
for(int i = h[u];i!=-1;i=ne[i]){
int j = e[i];
if(j == fa) continue;
if(choose[u]) choose[j] = false;
else{
choose[j] = dp[j][1] > dp[j][0] || (dp[j][1] == dp[j][0] && f[j][1] < f[j][0]);
}
DFS(j,u);
}
}
static void solve() {
int n = scan.nextInt();
Arrays.fill(h,-1);
for(int i = 1;i<n;i++){
int a = scan.nextInt();
int b = scan.nextInt();
add(a,b);
add(b,a);
}
if(n == 2){
System.out.println("2 2");
System.out.println("1 1");
}else{
dfs(1,-1);
int ans1 = Math.max(dp[1][1],dp[1][0]);
choose[1] = dp[1][1] > dp[1][0] || (dp[1][1] == dp[1][0] && f[1][1] < f[1][0]);
DFS(1,-1);
long res = 0;
for(int i = 1;i<=n;i++){
ans[i] = choose[i] ? d[i] : 1;
res += ans[i];
}
System.out.println(ans1 + " " + res);
for(int i = 1;i<=n;i++){
System.out.print(ans[i] + " ");
}
}
}
public static void main(String[] args) {
//int T = scan.nextInt();
//while (T-- > 0) {
solve();
//}
}
}
class AReader {
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer tokenizer = new StringTokenizer("");
private String innerNextLine() {
try {
return reader.readLine();
} catch (IOException ex) {
return null;
}
}
public boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String nextLine = innerNextLine();
if (nextLine == null) {
return false;
}
tokenizer = new StringTokenizer(nextLine);
}
return true;
}
public String nextLine() {
tokenizer = new StringTokenizer("");
return innerNextLine();
}
public String next() {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
class Pair {
int x,y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
| Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | c9df7ed5ad6b67322583cb5f802f82d8 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | // JAI SHREE RAM, HAR HAR MAHADEV, HARE KRISHNA
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.*;
import java.lang.*;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.io.*;
public class CodeForces {
static private final String INPUT = "input.txt";
static private final String OUTPUT = "output.txt";
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter out = new PrintWriter(System.out);
static DecimalFormat df = new DecimalFormat("0.00000");
final static int MAX = Integer.MAX_VALUE, MIN = Integer.MIN_VALUE, mod = (int) (1e9 + 7);
final static long LMAX = Long.MAX_VALUE, LMIN = Long.MIN_VALUE;
final static long INF = (long) 1e18, Neg_INF = (long) -1e18;
static Random rand = new Random();
// ======================= MAIN ==================================
public static void main(String[] args) throws IOException {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
// ==== start ====
input();
preprocess();
int t = 1;
// t = readInt();
while (t-- > 0) {
solve();
}
out.flush();
// ==== end ====
if (!oj)
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
private static void solve() throws IOException {
n = readInt();
tree = new ArrayList[n];
for (int i = 0; i < n; i++)
tree[i] = new ArrayList<>();
for (int i = 1; i < n; i++) {
int u = readInt() - 1, v = readInt() - 1;
tree[u].add(v);
tree[v].add(u);
}
if (n == 2) {
out.println("2 2\n1 1");
return;
}
dp = new Integer[n][2][2];
dfs(0, -1, 0);
dfs(0, -1, 1);
int[] ans = new int[n];
if (helper(dp[0][0], dp[0][1]) == dp[0][1]) {
out.println(dp[0][1][0] + " " + dp[0][1][1]);
helper(ans, dp[0][1], 0, -1);
} else {
out.println(dp[0][0][0] + " " + dp[0][0][1]);
helper(ans, dp[0][0], 0, -1);
}
printIArray(ans);
}
static int n;
static List<Integer>[] tree;
static Integer[][][] dp;
private static void dfs(int node, int par, int good) {
if (good == 1) {
dp[node][1][0] = 1;
dp[node][1][1] = tree[node].size();
} else {
dp[node][0][0] = 0;
dp[node][0][1] = 1;
}
for (int nbr : tree[node]) {
if (nbr == par)
continue;
if (dp[nbr][0][0] == null)
dfs(nbr, node, 0);
if (dp[nbr][1][0] == null)
dfs(nbr, node, 1);
if (good == 0 && helper(dp[nbr][0], dp[nbr][1]) == dp[nbr][1]) {
dp[node][good][0] += dp[nbr][1][0];
dp[node][good][1] += dp[nbr][1][1];
} else {
dp[node][good][0] += dp[nbr][0][0];
dp[node][good][1] += dp[nbr][0][1];
}
}
}
private static void helper(int[] ans, Integer[] arr, int node, int par) {
if (arr == dp[node][0]) {
ans[node] = 1;
for (int nbr : tree[node])
if (nbr != par)
helper(ans, helper(dp[nbr][0], dp[nbr][1]), nbr, node);
} else {
ans[node] = tree[node].size();
for (int nbr : tree[node])
if (nbr != par)
helper(ans, dp[nbr][0], nbr, node);
}
}
private static Integer[] helper(Integer[] a1, Integer[] a2) {
if (a1[0] > a2[0])
return a1;
if (a1[0] < a2[0])
return a2;
if (a1[1] < a2[1])
return a1;
return a2;
}
private static void preprocess() throws IOException {
}
// cd C:\Users\Eshan Bhatt\Visual Studio Code\Competitive Programming\CodeForces
// javac CodeForces.java
// java CodeForces
// javac CodeForces.java && java CodeForces
// change Stack size -> java -Xss16M CodeForces.java
// ==================== CUSTOM CLASSES ================================
static class Pair implements Comparable<Pair> {
int first, second;
Pair(int f, int s) {
first = f;
second = s;
}
public int compareTo(Pair o) {
if (this.first == o.first)
return this.second - o.second;
return this.first - o.first;
}
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (obj == null)
return false;
if (this.getClass() != obj.getClass())
return false;
Pair other = (Pair) (obj);
if (this.first != other.first)
return false;
if (this.second != other.second)
return false;
return true;
}
@Override
public int hashCode() {
return this.first ^ this.second;
}
@Override
public String toString() {
return this.first + " " + this.second;
}
}
static class DequeNode {
DequeNode prev, next;
int val;
DequeNode(int val) {
this.val = val;
}
DequeNode(int val, DequeNode prev, DequeNode next) {
this.val = val;
this.prev = prev;
this.next = next;
}
}
// ======================= FOR INPUT ==================================
private static void input() {
FileInputStream instream = null;
PrintStream outstream = null;
try {
instream = new FileInputStream(INPUT);
outstream = new PrintStream(new FileOutputStream(OUTPUT));
System.setIn(instream);
System.setOut(outstream);
} catch (Exception e) {
System.err.println("Error Occurred.");
}
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(readLine());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readCharacter() throws IOException {
return next().charAt(0);
}
static String readString() throws IOException {
return next();
}
static String readLine() throws IOException {
return br.readLine().trim();
}
static int[] readIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = readInt();
return arr;
}
static int[][] read2DIntArray(int n, int m) throws IOException {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
arr[i] = readIntArray(m);
return arr;
}
static List<Integer> readIntList(int n) throws IOException {
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(readInt());
return list;
}
static long[] readLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = readLong();
return arr;
}
static long[][] read2DLongArray(int n, int m) throws IOException {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++)
arr[i] = readLongArray(m);
return arr;
}
static List<Long> readLongList(int n) throws IOException {
List<Long> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(readLong());
return list;
}
static char[] readCharArray() throws IOException {
return readString().toCharArray();
}
static char[][] readMatrix(int n, int m) throws IOException {
char[][] mat = new char[n][m];
for (int i = 0; i < n; i++)
mat[i] = readCharArray();
return mat;
}
// ========================= FOR OUTPUT ==================================
private static void printIList(List<Integer> list) {
for (int i = 0; i < list.size(); i++)
out.print(list.get(i) + " ");
out.println(" ");
}
private static void printLList(List<Long> list) {
for (int i = 0; i < list.size(); i++)
out.print(list.get(i) + " ");
out.println(" ");
}
private static void printIArray(int[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println(" ");
}
private static void print2DIArray(int[][] arr) {
for (int i = 0; i < arr.length; i++)
printIArray(arr[i]);
}
private static void printLArray(long[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println(" ");
}
private static void print2DLArray(long[][] arr) {
for (int i = 0; i < arr.length; i++)
printLArray(arr[i]);
}
private static void yes() {
out.println("YES");
}
private static void no() {
out.println("NO");
}
// ====================== TO CHECK IF STRING IS NUMBER ========================
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
private static boolean isLong(String s) {
try {
Long.parseLong(s);
} catch (NumberFormatException e) {
return false;
} catch (NullPointerException e) {
return false;
}
return true;
}
// ==================== FASTER SORT ================================
private static void sort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void reverseSort(int[] arr) {
int n = arr.length;
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void sort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list);
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
private static void reverseSort(long[] arr) {
int n = arr.length;
List<Long> list = new ArrayList<>(n);
for (int i = 0; i < n; i++)
list.add(arr[i]);
Collections.sort(list, Collections.reverseOrder());
for (int i = 0; i < n; i++)
arr[i] = list.get(i);
}
// ==================== MATHEMATICAL FUNCTIONS ===========================
private static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private static int lcm(int a, int b) {
return (a / gcd(a, b)) * b;
}
private static long lcm(long a, long b) {
return (a / gcd(a, b)) * b;
}
private static int mod_pow(long a, long b, int mod) {
if (b == 0)
return 1;
int temp = mod_pow(a, b >> 1, mod);
temp %= mod;
temp = (int) ((1L * temp * temp) % mod);
if ((b & 1) == 1)
temp = (int) ((1L * temp * a) % mod);
return temp;
}
private static int multiply(int a, int b) {
return (int) ((((1L * a) % mod) * ((1L * b) % mod)) % mod);
}
private static int divide(int a, int b) {
return multiply(a, mod_pow(b, mod - 2, mod));
}
private static boolean isPrime(long n) {
for (long i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
private static long nCr(long n, long r) {
if (n - r > r)
r = n - r;
long ans = 1L;
for (long i = r + 1; i <= n; i++)
ans *= i;
for (long i = 2; i <= n - r; i++)
ans /= i;
return ans;
}
private static List<Integer> factors(int n) {
List<Integer> list = new ArrayList<>();
for (int i = 1; 1L * i * i <= n; i++)
if (n % i == 0) {
list.add(i);
if (i != n / i)
list.add(n / i);
}
return list;
}
private static List<Long> factors(long n) {
List<Long> list = new ArrayList<>();
for (long i = 1; i * i <= n; i++)
if (n % i == 0) {
list.add(i);
if (i != n / i)
list.add(n / i);
}
return list;
}
// ==================== Primes using Seive =====================
private static List<Integer> getPrimes(int n) {
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, true);
for (int i = 2; 1L * i * i <= n; i++)
if (prime[i])
for (int j = i * i; j <= n; j += i)
prime[j] = false;
// return prime;
List<Integer> list = new ArrayList<>();
for (int i = 2; i <= n; i++)
if (prime[i])
list.add(i);
return list;
}
private static int[] SeivePrime(int n) {
int[] primes = new int[n];
for (int i = 0; i < n; i++)
primes[i] = i;
for (int i = 2; 1L * i * i < n; i++) {
if (primes[i] != i)
continue;
for (int j = i * i; j < n; j += i)
if (primes[j] == j)
primes[j] = i;
}
return primes;
}
// ==================== STRING FUNCTIONS ================================
private static boolean isPalindrome(String str) {
int i = 0, j = str.length() - 1;
while (i < j)
if (str.charAt(i++) != str.charAt(j--))
return false;
return true;
}
// check if a is subsequence of b
private static boolean isSubsequence(String a, String b) {
int idx = 0;
for (int i = 0; i < b.length() && idx < a.length(); i++)
if (a.charAt(idx) == b.charAt(i))
idx++;
return idx == a.length();
}
private static String reverseString(String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
private static String sortString(String str) {
int[] arr = new int[256];
for (char ch : str.toCharArray())
arr[ch]++;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 256; i++)
while (arr[i]-- > 0)
sb.append((char) i);
return sb.toString();
}
// ==================== LIS & LNDS ================================
private static int LIS(int arr[], int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find1(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find1(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) >= val) {
ret = mid;
j = mid - 1;
} else {
i = mid + 1;
}
}
return ret;
}
private static int LNDS(int[] arr, int n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
int idx = find2(list, arr[i]);
if (idx < list.size())
list.set(idx, arr[i]);
else
list.add(arr[i]);
}
return list.size();
}
private static int find2(List<Integer> list, int val) {
int ret = list.size(), i = 0, j = list.size() - 1;
while (i <= j) {
int mid = (i + j) / 2;
if (list.get(mid) <= val) {
i = mid + 1;
} else {
ret = mid;
j = mid - 1;
}
}
return ret;
}
// =============== Lower Bound & Upper Bound ===========
// less than or equal
private static int lower_bound(List<Integer> list, int val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(List<Long> list, long val) {
int ans = -1, lo = 0, hi = list.size() - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(int[] arr, int val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
private static int lower_bound(long[] arr, long val) {
int ans = -1, lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] <= val) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
// greater than or equal
private static int upper_bound(List<Integer> list, int val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(List<Long> list, long val) {
int ans = list.size(), lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (list.get(mid) >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(int[] arr, int val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
private static int upper_bound(long[] arr, long val) {
int ans = arr.length, lo = 0, hi = ans - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (arr[mid] >= val) {
ans = mid;
hi = mid - 1;
} else {
lo = mid + 1;
}
}
return ans;
}
// ==================== UNION FIND =====================
private static int find(int x, int[] parent) {
if (parent[x] == x)
return x;
return parent[x] = find(parent[x], parent);
}
private static boolean union(int x, int y, int[] parent, int[] rank) {
int lx = find(x, parent), ly = find(y, parent);
if (lx == ly)
return false;
if (rank[lx] > rank[ly])
parent[ly] = lx;
else if (rank[lx] < rank[ly])
parent[lx] = ly;
else {
parent[lx] = ly;
rank[ly]++;
}
return true;
}
// ==================== TRIE ================================
static class Trie {
class Node {
Node[] children;
boolean isEnd;
Node() {
children = new Node[26];
}
}
Node root;
Trie() {
root = new Node();
}
void insert(String word) {
Node curr = root;
for (char ch : word.toCharArray()) {
if (curr.children[ch - 'a'] == null)
curr.children[ch - 'a'] = new Node();
curr = curr.children[ch - 'a'];
}
curr.isEnd = true;
}
boolean find(String word) {
Node curr = root;
for (char ch : word.toCharArray()) {
if (curr.children[ch - 'a'] == null)
return false;
curr = curr.children[ch - 'a'];
}
return curr.isEnd;
}
}
// ================== SEGMENT TREE (RANGE SUM & RANGE UPDATE) ==================
public static class SegmentTree {
int n;
long[] arr, tree, lazy;
SegmentTree(long arr[]) {
this.arr = arr;
this.n = arr.length;
this.tree = new long[(n << 2)];
this.lazy = new long[(n << 2)];
build(1, 0, n - 1);
}
void build(int id, int start, int end) {
if (start == end)
tree[id] = arr[start];
else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
build(left, start, mid);
build(right, mid + 1, end);
tree[id] = tree[left] + tree[right];
}
}
void update(int l, int r, long val) {
update(1, 0, n - 1, l, r, val);
}
void update(int id, int start, int end, int l, int r, long val) {
distribute(id, start, end);
if (end < l || r < start)
return;
if (start == end)
tree[id] += val;
else if (l <= start && end <= r) {
lazy[id] += val;
distribute(id, start, end);
} else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
update(left, start, mid, l, r, val);
update(right, mid + 1, end, l, r, val);
tree[id] = tree[left] + tree[right];
}
}
long query(int l, int r) {
return query(1, 0, n - 1, l, r);
}
long query(int id, int start, int end, int l, int r) {
if (end < l || r < start)
return 0L;
distribute(id, start, end);
if (start == end)
return tree[id];
else if (l <= start && end <= r)
return tree[id];
else {
int mid = (start + end) / 2, left = (id << 1), right = left + 1;
return query(left, start, mid, l, r) + query(right, mid + 1, end, l, r);
}
}
void distribute(int id, int start, int end) {
if (start == end)
tree[id] += lazy[id];
else {
tree[id] += lazy[id] * (end - start + 1);
lazy[(id << 1)] += lazy[id];
lazy[(id << 1) + 1] += lazy[id];
}
lazy[id] = 0;
}
}
// ==================== FENWICK TREE ================================
static class FT {
int n;
int[] arr;
int[] tree;
FT(int[] arr, int n) {
this.arr = arr;
this.n = n;
this.tree = new int[n + 1];
for (int i = 1; i <= n; i++) {
update(i, arr[i - 1]);
}
}
FT(int n) {
this.n = n;
this.tree = new int[n + 1];
}
// 1 based indexing
void update(int idx, int val) {
while (idx <= n) {
tree[idx] += val;
idx += idx & -idx;
}
}
// 1 based indexing
long query(int l, int r) {
return getSum(r) - getSum(l - 1);
}
long getSum(int idx) {
long ans = 0L;
while (idx > 0) {
ans += tree[idx];
idx -= idx & -idx;
}
return ans;
}
}
// ==================== BINARY INDEX TREE ================================
static class BIT {
long[][] tree;
int n, m;
BIT(int[][] mat, int n, int m) {
this.n = n;
this.m = m;
tree = new long[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
update(i, j, mat[i - 1][j - 1]);
}
}
}
void update(int x, int y, int val) {
while (x <= n) {
int t = y;
while (t <= m) {
tree[x][t] += val;
t += t & -t;
}
x += x & -x;
}
}
long query(int x1, int y1, int x2, int y2) {
return getSum(x2, y2) - getSum(x1 - 1, y2) - getSum(x2, y1 - 1) + getSum(x1 - 1, y1 - 1);
}
long getSum(int x, int y) {
long ans = 0L;
while (x > 0) {
int t = y;
while (t > 0) {
ans += tree[x][t];
t -= t & -t;
}
x -= x & -x;
}
return ans;
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 59db097e243a54f39324a8e60f78df14 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import javax.swing.text.Segment;
import java.util.*;
import java.io.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
public class Solution
{
private static class FastIO {
private static class FastReader
{
BufferedReader br;
StringTokenizer st;
FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
private static PrintWriter out = new PrintWriter(System.out);
private static FastReader in = new FastReader();
public void print(String s) {out.print(s);}
public void println(String s) {out.println(s);}
public void println() {
println("");
}
public void print(int i) {out.print(i);}
public void print(long i) {out.print(i);}
public void print(char i) {out.print(i);}
public void print(double i) {out.print(i);}
public void println(int i) {out.println(i);}
public void println(long i) {out.println(i);}
public void println(char i) {out.println(i);}
public void println(double i) {out.println(i);}
public void printIntArrayWithoutSpaces(int[] a) {
for(int i : a) {
out.print(i);
}
out.println();
}
public void printIntArrayWithSpaces(int[] a) {
for(int i : a) {
out.print(i + " ");
}
out.println();
}
public int[] getIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) {
res[i] = in.nextInt();
}
return res;
}
public static List<Integer> getIntList(int n) {
List<Integer> list = new ArrayList<>();
for(int i = 0; i < n; i++) {
list.add(in.nextInt());
}
return list;
}
public static void printKickstartCase(int i) {
out.print("Case #" + i + ": ");
}
public String next() {return in.next();}
int nextInt() { return in.nextInt(); }
char nextChar() {return in.next().charAt(0);}
long nextLong() { return in.nextLong(); }
double nextDouble() { return in.nextDouble(); }
String nextLine() {return in.nextLine();}
public void close() {
out.flush();
out.close();
}
}
private static final FastIO io = new FastIO();
private static class MathUtil {
public static final int MOD = 1000000007;
public static int gcd(int a, int b) {
if(b == 0) {
return a;
}
return gcd(b, a % b);
}
public static int gcd(int[] a) {
if(a.length == 0) {
return 0;
}
int res = a[0];
for(int i = 1; i < a.length; i++) {
res = gcd(res, a[i]);
}
return res;
}
public static int gcd(List<Integer> a) {
if(a.size() == 0) {
return 0;
}
int res = a.get(0);
for(int i = 1; i < a.size(); i++) {
res = gcd(res, a.get(i));
}
return res;
}
public static int modular_mult(int a, int b, int M) {
long res = (long)a * b;
return (int)(res % M);
}
public static int modular_mult(int a, int b) {
return modular_mult(a, b, MOD);
}
public static int modular_add(int a, int b, int M) {
long res = (long)a + b;
return (int)(res % M);
}
public static int modular_add(int a, int b) {
return modular_add(a, b, MOD);
}
public static int modular_sub(int a, int b, int M) {
long res = ((long)a - b) + M;
return (int)(res % M);
}
public static int modular_sub(int a, int b) {
return modular_sub(a, b, MOD);
}
//public static int modular_div(int a, int b, int M) {}
//public static int modular_div(int a, int b) {return modular_div(a, b, MOD);}
public static int pow(int a, int b, int M) {
int res = 1;
while (b > 0) {
if ((b & 1) == 1) {
res = modular_mult(res, a, M);
}
a = modular_mult(a, a, M);
b = b >> 1;
}
return res;
}
public static int pow(int a, int b) {
return pow(a, b, MOD);
}
/*public static int fact(int i, int M) {
}
public static int fact(int i) {
}
public static void preComputeFact(int i) {
}
public static int mod_mult_inverse(int den, int mod) {
}
public static void C(int n, int r) {
}*/
}
private static class ArrayUtil {
@FunctionalInterface
private static interface NumberPairComparator {
boolean test(int a, int b);
}
public static int[] nextGreaterOrSmallerRight(int[] a, NumberPairComparator npc) {
int n = a.length;
int[] res = new int[n];
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < n; i++) {
int cur = a[i];
while(!stack.isEmpty() && npc.test(a[stack.peek()], cur)) {
res[stack.pop()] = i;
}
stack.push(i);
}
while(!stack.isEmpty()) {
res[stack.pop()] = n;
}
return res;
}
public static int[] nextGreaterOrSmallerLeft(int[] a, NumberPairComparator npc) {
int n = a.length;
int[] res = new int[n];
Stack<Integer> stack = new Stack<>();
for(int i = n - 1; i >= 0; i--) {
int cur = a[i];
while(!stack.isEmpty() && npc.test(a[stack.peek()], cur)) {
res[stack.pop()] = i;
}
stack.push(i);
}
while(!stack.isEmpty()) {
res[stack.pop()] = n;
}
return res;
}
public static Map<Integer, Integer> getFreqMap(int[] a) {
Map<Integer, Integer> map = new HashMap<>();
for(int i : a) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
return map;
}
public static long arraySum(int[] a) {
long sum = 0;
for(int i : a) {
sum += i;
}
return sum;
}
}
private static final int M = 1000000007;
private static final String yes = "YES";
private static final String no = "NO";
private static final int MAX = M / 100;
private static final int MIN = -MAX;
private static final int UNVISITED = -1;
private static class Tree {
List<List<Integer>> list;
int n;
Tree(int n) {
this.n = n;
list = new ArrayList<>();
for(int i = 0; i < n; i++) {
list.add(new ArrayList<>());
}
}
public void addUndirectedEdge(int a, int b) {
list.get(a).add(b);
list.get(b).add(a);
}
public boolean isLeaf(int i) {
return (i != 0 && getNeighbours(i).size() == 1);
}
public List<Integer> getNeighbours(int i) {
return list.get(i);
}
//@FunctionalInterface
/*private interface DfsAction<T> {
void perform(int parent, int child, List<T> values);
}
private <T> void dfs(int node, int parent, DfsAction<T> preOrderAction, DfsAction<T> postOrderAction, DfsAction<T> rootAction, DfsAction<T> leafAction, List<T> values) {
if(node == 0) {
rootAction.perform(parent, node, values);
}
if(isLeaf(node)) {
leafAction.perform(parent, node, values);
}
preOrderAction.perform(parent, node, values);
List<Integer> children = getNeighbours(node);
for(int child : children) {
if(child == parent) {
continue;
}
dfs(child, node, preOrderAction, postOrderAction, leafAction, rootAction, values);
postOrderAction.perform(node, child, values);
}
}
public <T> void dfs(int root, DfsAction<T> preOrderAction, DfsAction<T> postOrderAction, DfsAction<T> rootAction, DfsAction<T> leafAction, List<T> values) {
dfs(0, -1, preOrderAction, postOrderAction, rootAction, leafAction, values);
}*/
}
private static long sumOfMask(int mask, List<Long> list) {
long res = 0;
int bit_pos = 0;
while(mask > 0) {
if((mask & 1) == 1) {
res += list.get(bit_pos);
}
bit_pos ++;
mask >>= 1;
}
return res;
}
private static class Pair {
int cur;
int parent;
public Pair(int cur, int parent) {
this.cur = cur;
this.parent = parent;
}
}
private static int[][] dp;
private static int[][] dp_weight;
private static List<Set<Integer>> good_list;
private static void dfs(int node, int parent, Tree tree) {
if(tree.isLeaf(node)) {
dp[node][0] = 1;
dp[node][1] = 0;
dp_weight[node][0] = 1;
dp_weight[node][1] = 1;
return;
}
List<Integer> nei = tree.getNeighbours(node);
dp[node][0] = 1;
dp_weight[node][1] = 1;
dp_weight[node][0] = tree.getNeighbours(node).size();
for(int ne : nei) {
if(ne == parent) {
continue;
}
dfs(ne, node, tree);
dp[node][0] += dp[ne][1];
dp_weight[node][0] += (dp_weight[ne][1]);
if(dp[ne][0] > dp[ne][1]) {
good_list.get(node).add(ne);
dp[node][1] += dp[ne][0];
dp_weight[node][1] += dp_weight[ne][0];
}
else if(dp[ne][0] < dp[ne][1]) {
dp[node][1] += dp[ne][1];
dp_weight[node][1] += dp_weight[ne][1];
}
else {
if(dp_weight[ne][0] <= dp_weight[ne][1]) {
good_list.get(node).add(ne);
dp[node][1] += dp[ne][0];
dp_weight[node][1] += dp_weight[ne][0];
}
else {
dp[node][1] += dp[ne][1];
dp_weight[node][1] += dp_weight[ne][1];
}
}
}
}
static Set<Integer> good;
private static void dfs2(int node, int parent, Tree tree, boolean b) {
if(b) {
good.add(node);
}
if(tree.isLeaf(node)) {
return;
}
List<Integer> neighbours = tree.getNeighbours(node);
for(int ne : neighbours) {
if(ne == parent) {
continue;
}
if(b) {
dfs2(ne, node, tree, false);
}
else {
dfs2(ne, node, tree, good_list.get(node).contains(ne));
}
}
}
public static void main(String[] args)
{
//int t = io.nextInt();
int t = 1;
for(int z = 0; z < t; z ++) {
int n = io.nextInt();
dp = new int[n][2];
dp_weight = new int[n][2];
good_list = new ArrayList<>();
good = new HashSet<>();
for(int i = 0; i < n; i++) {
good_list.add(new HashSet<>());
}
Tree tree = new Tree(n);
for(int i = 0; i < n - 1; i++) {
tree.addUndirectedEdge(io.nextInt() - 1, io.nextInt() - 1);
}
if(n == 2) {
io.println("2 2");
io.println("1 1");
continue;
}
dfs(0, -1, tree);
boolean root_is_good = false;
if(dp[0][0] > dp[0][1]) {
root_is_good = true;
}
else if(dp[0][0] < dp[0][1]) {
root_is_good = false;
}
else {
if(dp_weight[0][0] <= dp_weight[0][1]) {
root_is_good = true;
}
else {
root_is_good = false;
}
}
dfs2(0, -1, tree, root_is_good);
int n1 = Math.max(dp[0][0], dp[0][1]);
int weight = 0;
for(int i : good) {
weight += tree.getNeighbours(i).size();
}
weight += (n - n1);
io.println("" + n1 + " " + weight);
for(int i = 0; i < n; i++) {
if(good.contains(i)) {
io.print(tree.getNeighbours(i).size() + " ");
}
else {
io.print("1 ");
}
}
io.println();
}
io.close();
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | c63f76c33791fca8a40b54a9c4cb08e2 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
Solution Created: 20:24:10 04/03/2022
Custom Competitive programming helper.
*/
public class Main {
static ArrayList<Integer> adj[];
public static void solve() {
n = in.nextInt();
adj = new ArrayList[n];
for(int i = 0; i<n; i++) adj[i] = new ArrayList<>();
for(int i = 0; i<n-1; i++) {
int u = in.nextInt()-1, v = in.nextInt()-1;
adj[u].add(v);
adj[v].add(u);
}
if(n == 2) {
out.println("2 2");
out.println("1 1");
return;
}
dp = new int[n][2];
dpWeight = new int[n][2];
taken = new HashMap<>();
for(int i = 0; i<n; i++)taken.put(i, new HashSet<>());
assignment = new int[n];
totWeigth = 0;
good = 0;
vis = 0;
dfs(0,-1);
good = Math.max(dp[0][1],dp[0][0]);
if(dp[0][1]>dp[0][0]) {
dfs2(0,-1,true);
}else if(dp[0][1]<dp[0][0]) {
dfs2(0,-1,false);
}else {
if(dpWeight[0][1]>dpWeight[0][0]) {
dfs2(0,-1,false);
}else {
dfs2(0,-1,true);
}
}
out.println(good+" "+totWeigth);
out.printlnArray(assignment);
}
static int n;
static int good;
static int[] assignment;
static int totWeigth;
static HashMap<Integer, HashSet<Integer>> taken = new HashMap<>();
static int[][] dp;
static int[][] dpWeight;
static int vis = 0;
public static void dfs2(int i, int p, boolean take) {
if(take) {
assignment[i] = adj[i].size();
}else {
assignment[i] = 1;
}
totWeigth += assignment[i];
for(int j : adj[i]) {
if(j == p) continue;
if(!take) {
if(taken.get(i).contains(j)) dfs2(j, i, true);
else dfs2(j, i, false);
}else {
dfs2(j, i, false);
}
}
}
public static void dfs(int i, int p) {
for(int j : adj[i]) {
if(j == p) continue;
dfs(j,i);
}
dpWeight[i][0] = 1;
for(int j : adj[i]) {
//Handle case where we take
dp[i][1] += dp[j][0]; //if we take, we must not take our neighbors;
dpWeight[i][1] += dpWeight[j][0];
//Handle case where we don't take: if we don't take, we can either take or not take our neighbors;
if(dp[j][0] > dp[j][1]) {
dp[i][0] += dp[j][0];
dpWeight[i][0] += dpWeight[j][0];
}else if(dp[j][0] < dp[j][1]) {
taken.get(i).add(j);
dp[i][0] += dp[j][1];
dpWeight[i][0] += dpWeight[j][1];
}else {
if(dpWeight[j][1]>dpWeight[j][0]) {
dp[i][0] += dp[j][0];
dpWeight[i][0] += dpWeight[j][0];
}else {
taken.get(i).add(j);
dp[i][0] += dp[j][1];
dpWeight[i][0] += dpWeight[j][1];
}
}
}
dp[i][1]++;
dpWeight[i][1] += adj[i].size();
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = 1;
while(t-->0) solve();
out.exit();
}
static Reader in; static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
this.br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public char[] nca() {
return next().toCharArray();
}
public String[] ns(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = next();
return a;
}
public int nextInt() {
ensureNext();
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
ensureNext();
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
ensureNext();
return Long.parseLong(st.nextToken());
}
public String next() {
ensureNext();
return st.nextToken();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void ensureNext() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Util{
private static Random random = new Random();
static long[] fact;
public static void initFactorial(int n, long mod) {
fact = new long[n+1];
fact[0] = 1;
for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod;
}
public static long modInverse(long a, long MOD) {
long[] gcdE = gcdExtended(a, MOD);
if (gcdE[0] != 1) return -1; // Inverted doesn't exist
long x = gcdE[1];
return (x % MOD + MOD) % MOD;
}
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
public static long nCr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nCr(int n, int r) {
return (fact[n]/fact[r])/fact[n-r];
}
public static long nPr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nPr(int n, int r) {
return fact[n]/fact[n-r];
}
public static boolean 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;
}
public static boolean[] getSieve(int n) {
boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i*i <= n; i++) if (isPrime[i])
for (int j = i; i*j <= n; j++) isPrime[i*j] = false;
return isPrime;
}
static long pow(long x, long pow, long mod){
long res = 1;
x = x % mod;
if (x == 0) return 0;
while (pow > 0){
if ((pow & 1) != 0) res = (res * x) % mod;
pow >>= 1;
x = (x * x) % mod;
}
return res;
}
public static int gcd(int a, int b) {
int tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static int random(int min, int max) {
return random.nextInt(max-min+1)+min;
}
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void reverse(int[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
int tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(long[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
long tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(float[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
float tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(double[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
double tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(char[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
char tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(char[] s) {
reverse(s, 0, s.length-1);
}
public static <T> void reverse(T[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
T tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length-1);
}
public static void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(long[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
long t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(char[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
public static int[][] rotate90(int[][] a){
int n = a.length, m = a[0].length;
int[][] ans = new int[m][n];
for(int i = 0; i<n; i++) for(int j = 0; j<m; j++) ans[m-j-1][i] = a[i][j];
return ans;
}
public static char[][] rotate90(char[][] a){
int n = a.length, m = a[0].length;
char[][] ans = new char[m][n];
for(int i = 0; i<n; i++) for(int j = 0; j<m; j++) ans[m-j-1][i] = a[i][j];
return ans;
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public void yesNo(boolean condition) {
println(condition?"YES":"NO");
}
public void printArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void printArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void print(Object o) {
pw.print(o.toString());
}
public void println(Object o) {
pw.println(o.toString());
}
public void println() {
pw.println();
}
public void flush() {
pw.flush();
}
public void exit() {
pw.close();
}
}
}
| Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 88f06192cca6ed9bcfb4118a9af70c9c | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.function.Function;
public class Solution {
// VM options: -Xmx1024m -Xss1024m
private void solve() throws IOException {
int n = nextInt();
var g = new Graph(n);
for (int i = 1; i < n; i++) {
int t1 = nextInt() - 1;
int t2 = nextInt() - 1;
g.addIndirect(t1, t2);
}
if (n == 2) {
out.println("2 2\n1 1");
return;
}
int v = 0;
for (int i = 0; i < n; i++) {
if (g.neighbors(i).size() > 1) {
v = i;
break;
}
}
isGood = new boolean[n];
dTraceGood = new boolean[n];
dWeightGood = new int[n];
dWeightBad = new int[n];
dCountGood = new int[n];
dCountBad = new int[n];
dfs(v, -1, g);
boolean isGoodV;
if (dCountBad[v] > dCountGood[v] || (dCountBad[v] == dCountGood[v] && dWeightBad[v] < dWeightGood[v])) {
out.println(dCountBad[v] + " " + dWeightBad[v]);
isGoodV = false;
} else {
out.println(dCountGood[v] + " " + dWeightGood[v]);
isGoodV = true;
}
dfs2(v, -1, g, isGoodV);
for (int i = 0; i < n; i++) {
out.print((isGood[i] ? g.neighbors(i).size() : 1) + " ");
}
out.println();
}
private void dfs2(int v, int p, Graph g, boolean isGoodV) {
isGood[v] = isGoodV;
for (int nv : g.neighbors(v)) {
if (p != nv) {
if (isGoodV) {
dfs2(nv, v, g, false);
} else {
dfs2(nv, v, g, dTraceGood[nv]);
}
}
}
}
private void dfs(int v, int p, Graph g) {
int sumBad = 0;
int sumAll = 0;
int countBad = 0;
int countAll = 0;
for (int nv : g.neighbors(v)) {
if (p != nv) {
dfs(nv, v, g);
sumBad += dWeightBad[nv];
countBad += dCountBad[nv];
if (dCountBad[nv] > dCountGood[nv] || (dCountBad[nv] == dCountGood[nv] && dWeightBad[nv] < dWeightGood[nv])) {
sumAll += dWeightBad[nv];
countAll += dCountBad[nv];
} else {
sumAll += dWeightGood[nv];
countAll += dCountGood[nv];
dTraceGood[nv] = true;
}
}
}
dCountGood[v] = 1 + countBad;
dWeightGood[v] = sumBad + g.neighbors(v).size();
dCountBad[v] = countAll;
dWeightBad[v] = 1 + sumAll;
}
private int[] dWeightGood;
private int[] dWeightBad;
private int[] dCountGood;
private int[] dCountBad;
private boolean[] dTraceGood;
private boolean[] isGood;
private static class Graph {
private ArrayList<Integer>[] g;
public Graph(int n) {
g = new ArrayList[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
}
}
public void addDirect(int u, int v) {
g[u].add(v);
}
public void addIndirect(int u, int v) {
g[u].add(v);
g[v].add(u);
}
public ArrayList<Integer> neighbors(int v) {
return g[v];
}
}
private static final String inputFilename = "input.txt";
private static final String outputFilename = "output.txt";
private BufferedReader in;
private StringTokenizer line;
private PrintWriter out;
private final boolean isDebug;
private Solution(boolean isDebug) {
this.isDebug = isDebug;
}
public static void main(String[] args) throws IOException {
new Solution(Arrays.asList(args).contains("DEBUG_MODE")).run(args);
}
private void run(String[] args) throws IOException {
if (isDebug) {
in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFilename)));
// in = new BufferedReader(new InputStreamReader(System.in));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
}
out = new PrintWriter(System.out);
// out = new PrintWriter(outputFilename);
int t = isDebug ? nextInt() : 1;
// int t = nextInt();
// int t = 1;
for (int i = 0; i < t; i++) {
// out.print("Case #" + (i + 1) + ": ");
solve();
out.flush();
}
in.close();
out.flush();
out.close();
}
private void println(Object... objects) {
boolean isFirst = true;
for (Object o : objects) {
if (!isFirst) {
out.print(" ");
} else {
isFirst = false;
}
out.print(o.toString());
}
out.println();
}
private int[] nextIntArray(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
private long[] nextLongArray(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong();
}
return res;
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private String nextToken() throws IOException {
while (line == null || !line.hasMoreTokens()) {
line = new StringTokenizer(in.readLine());
}
return line.nextToken();
}
private static void assertPredicate(boolean p) {
if (!p) {
throw new RuntimeException();
}
}
private static void assertPredicate(boolean p, String message) {
if (!p) {
throw new RuntimeException(message);
}
}
private static void assertNotEqual(int unexpected, int actual) {
if (actual == unexpected) {
throw new RuntimeException("assertNotEqual: " + unexpected + " == " + actual);
}
}
private static void assertEqual(int expected, int actual) {
if (expected != actual) {
throw new RuntimeException("assertEqual: " + expected + " != " + actual);
}
}
}
| Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 60d7f1c7381699956bd4ee091fc5fc5f | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.util.*;
import java.io.*;
public class D1646 {
static ArrayList<Integer>[] adjList;
static int[][][] dp;
static int[] max(int[] a, int[] b) {
if (a[0] > b[0]) {
return a;
} else if (b[0] > a[0]) {
return b;
} else if (a[1] < b[1]) {
return a;
} else {
return b;
}
}
static void add(int[] ans, int[] a) {
ans[0] += a[0];
ans[1] += a[1];
}
static int[] dp(int u, int p, int state) {
if (dp[state][u] != null) {
return dp[state][u];
}
int[] ans = new int[2];
if (state == 0) {
for (int v : adjList[u]) {
if (v == p) {
continue;
}
add(ans, max(dp(v, u, 0), dp(v, u, 1)));
}
ans[1] += 1;
} else {
for (int v : adjList[u]) {
if (v == p) {
continue;
}
add(ans, dp(v, u, 0));
}
ans[0]++;
ans[1] += adjList[u].size();
}
return dp[state][u] = ans;
}
static void trace(int u, int p, int state, int[] color) {
if (state == 0) {
for (int v : adjList[u]) {
if (v == p) {
continue;
}
if (max(dp(v, u, 0), dp(v, u, 1)) == dp(v, u, 0)) {
trace(v, u, 0, color);
} else {
trace(v, u, 1, color);
}
}
color[u] = 1;
} else {
for (int v : adjList[u]) {
if (v == p) {
continue;
}
trace(v, u, 0, color);
}
color[u] = adjList[u].size();
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
adjList = new ArrayList[n];
for (int i = 0; i < n; i++) {
adjList[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
adjList[u].add(v);
adjList[v].add(u);
}
if (n == 2) {
pw.println("2 2");
pw.println("1 1");
pw.close();
return;
}
dp = new int[2][n][];
int[] color = new int[n];
int[] ans = max(dp(0, -1, 0), dp(0, -1, 1));
if (ans == dp(0, -1, 0)) {
trace(0, -1, 0, color);
} else {
trace(0, -1, 1, color);
}
pw.println(ans[0] + " " + ans[1]);
for (int x : color) {
pw.print(x + " ");
}
pw.println();
pw.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader f) {
br = new BufferedReader(f);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(next());
}
return arr;
}
}
}
| Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 3a9eda96a5e5f6ab3d608f4a9ea1bbf7 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | //Utilities
import java.io.*;
import java.util.*;
public class a {
static int t;
static int n;
static ArrayList<Integer>[] adj;
static int u, v;
static Pair[][] dp;
static boolean[][] b;
static int[] res;
public static void main(String[] args) throws IOException {
t = 1;
outer : while (t-- > 0) {
n = in.iscan(); adj = new ArrayList[n+1];
for (int i = 0; i <= n; i++) {
adj[i] = new ArrayList<Integer>();
}
for (int i = 0; i < n-1; i++) {
u = in.iscan(); v = in.iscan();
adj[u].add(v); adj[v].add(u);
}
if (n == 2) {
out.println(2 + " " + 2);
out.println(1 + " " + 1);
continue outer;
}
dp = new Pair[n+1][2]; // [idx][can take]
b = new boolean[n+1][2];
dfs(1, -1, 1);
Pair p = isBetter(dp[1][0], dp[1][1]) ? dp[1][0] : dp[1][1];
out.println(p.c + " " + p.v);
res = new int[n+1];
constructRes(1, -1, 1);
for (int i = 1; i <= n; i++) {
out.print(res[i] + " ");
}
out.println();
}
out.close();
}
static void constructRes(int idx, int prev, int canTake) {
if (b[idx][canTake]) {
res[idx] = adj[idx].size();
for (int u : adj[idx]) {
if (u != prev) {
constructRes(u, idx, 0);
}
}
}
else {
res[idx] = 1;
for (int u : adj[idx]) {
if (u != prev) {
constructRes(u, idx, 1);
}
}
}
}
static void dfs(int idx, int prev, int canTake) {
if (dp[idx][canTake] != null) {
return;
}
int newCnt0 = 0; long newSum0 = 1; // if not take idx
int newCnt1 = 1; long newSum1 = adj[idx].size(); // if take idx
for (int u : adj[idx]) {
if (u != prev) {
dfs(u, idx, 1);
dfs(u, idx, 0);
newCnt0 += dp[u][1].c; newSum0 += dp[u][1].v;
newCnt1 += dp[u][0].c; newSum1 += dp[u][0].v;
// out.println(idx + " " + u + " " + canTake + " " + newCnt0 + " " + newSum0 + " " + newCnt1 + " " + newSum1);
}
}
int newCnt; long newSum;
if (canTake == 0) {
newCnt = newCnt0; newSum = newSum0;
b[idx][canTake] = false;
}
else {
if (newCnt0 > newCnt1 || newCnt0 == newCnt1 && newSum0 <= newSum1) {
newCnt = newCnt0; newSum = newSum0;
b[idx][canTake] = false;
}
else {
newCnt = newCnt1; newSum = newSum1;
b[idx][canTake] = true;
}
}
dp[idx][canTake] = new Pair(newCnt, newSum);
// out.println(idx + " " + canTake + " " + newCnt + " " + newSum);
return;
}
static boolean isBetter(Pair a, Pair b) {
if (a == null) return false;
if (b == null) return true;
return a.c > b.c || a.c == b.c && a.v <= b.v;
}
static class Pair {
int c; long v;
Pair(int c, long v){
this.c = c; this.v = v;
}
public String toString() {
return "(" + c + ", " + v + ")";
}
}
static INPUT in = new INPUT(System.in);
static PrintWriter out = new PrintWriter(System.out);
private static class INPUT {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public INPUT (InputStream stream) {
this.stream = stream;
}
public INPUT (String file) throws IOException {
this.stream = new FileInputStream (file);
}
public int cscan () throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read (buf);
}
if (numChars == -1)
return numChars;
return buf[curChar++];
}
public int iscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
int res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public String sscan () throws IOException {
int c = cscan ();
while (space (c))
c = cscan ();
StringBuilder res = new StringBuilder ();
do {
res.appendCodePoint (c);
c = cscan ();
}
while (!space (c));
return res.toString ();
}
public double dscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
double res = 0;
while (!space (c) && c != '.') {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
res *= 10;
res += c - '0';
c = cscan ();
}
if (c == '.') {
c = cscan ();
double m = 1;
while (!space (c)) {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
m /= 10;
res += (c - '0') * m;
c = cscan ();
}
}
return res * sgn;
}
public long lscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
long res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public boolean space (int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
public static class UTILITIES {
static final double EPS = 10e-6;
public static void sort(int[] a, boolean increasing) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(long[] a, boolean increasing) {
ArrayList<Long> arr = new ArrayList<Long>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(double[] a, boolean increasing) {
ArrayList<Double> arr = new ArrayList<Double>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static int lower_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static void updateMap(HashMap<Integer, Integer> map, int key, int v) {
if (!map.containsKey(key)) {
map.put(key, v);
}
else {
map.put(key, map.get(key) + v);
}
if (map.get(key) == 0) {
map.remove(key);
}
}
public static long gcd (long a, long b) {
return b == 0 ? a : gcd (b, a % b);
}
public static long lcm (long a, long b) {
return a * b / gcd (a, b);
}
public static long fast_pow_mod (long b, long x, int mod) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod;
return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod;
}
public static long fast_pow (long b, long x) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow (b * b, x / 2);
return b * fast_pow (b * b, x / 2);
}
public static long choose (long n, long k) {
k = Math.min (k, n - k);
long val = 1;
for (int i = 0; i < k; ++i)
val = val * (n - i) / (i + 1);
return val;
}
public static long permute (int n, int k) {
if (n < k) return 0;
long val = 1;
for (int i = 0; i < k; ++i)
val = (val * (n - i));
return val;
}
// start of permutation and lower/upper bound template
public static void nextPermutation(int[] nums) {
//find first decreasing digit
int mark = -1;
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
mark = i - 1;
break;
}
}
if (mark == -1) {
reverse(nums, 0, nums.length - 1);
return;
}
int idx = nums.length-1;
for (int i = nums.length-1; i >= mark+1; i--) {
if (nums[i] > nums[mark]) {
idx = i;
break;
}
}
swap(nums, mark, idx);
reverse(nums, mark + 1, nums.length - 1);
}
public static void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void reverse(int[] nums, int i, int j) {
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
static int lower_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= cmp) high = mid;
else low = mid + 1;
}
return low;
}
static int upper_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > cmp) high = mid;
else low = mid + 1;
}
return low;
}
// end of permutation and lower/upper bound template
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | c08d2948d33fb36af3f7d8d272c9804e | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.*;
import java.util.*;
public class new1{
static long mod = 1000000007;
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
public static int[] dfs1(ArrayList<ArrayList<Integer>> aList, int u, int v, int p, int[][][] dp) {
if(dp[u][v] != null) return dp[u][v];
int sum1 = 0; int sum2 = 0;
for(Integer x : aList.get(u)) {
if(x != p) {
if(v == 1) {
sum1 = sum1 + dfs1(aList, x, 0, u, dp)[0];
sum2 = sum2 + dfs1(aList, x, 0, u, dp)[1];
}
else {
int aa1 = 0; int aa2 = 0;
if(dfs1(aList, x, 0, u, dp)[0] > dfs1(aList, x, 1, u, dp)[0]) {
aa1 = dfs1(aList, x, 0, u, dp)[0];
aa2 = dfs1(aList, x, 0, u, dp)[1];
}
else if(dfs1(aList, x, 0, u, dp)[0] < dfs1(aList, x, 1, u, dp)[0]) {
aa1 = dfs1(aList, x, 1, u, dp)[0];
aa2 = dfs1(aList, x, 1, u, dp)[1];
}
else {
aa1 = dfs1(aList, x, 1, u, dp)[0];
aa2 = Math.min(dfs1(aList, x, 1, u, dp)[1], dfs1(aList, x, 0, u, dp)[1]);
}
sum1 = sum1 + aa1;
sum2 = sum2 + aa2;
}
}
}
if(v == 1) {
sum1 = sum1 + 1;
sum2 = sum2 + aList.get(u).size();
}
else sum2 = sum2 + 1;
int[] aaa = {sum1, sum2};
dp[u][v] = aaa;
return aaa;
}
public static void dfs2(ArrayList<ArrayList<Integer>> aList, int u, int p, int st, int[][][] dp, int[] arr) {
if(st == 1) {
if(dfs1(aList, u, 0, p, dp)[0] > dfs1(aList, u, 1, p, dp)[0]) st = 0;
else if(dfs1(aList, u, 0, p, dp)[0] == dfs1(aList, u, 1, p, dp)[0]) {
if(dfs1(aList, u, 0, p, dp)[1] <= dfs1(aList, u, 1, p, dp)[1]) st = 0;
}
}
for(Integer x : aList.get(u)) {
if(x != p) {
if(st == 0) dfs2(aList, x, u, 1, dp, arr);
else dfs2(aList, x, u, 0, dp, arr);
}
}
if(st == 1) arr[u] = 1;
}
public static void main(String[] args) throws IOException{
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
FastReader s = new FastReader();
int t = 1;//s.nextInt();
for(int z = 0; z < t; z++) {
int n = s.nextInt();
ArrayList<ArrayList<Integer>> aList = new ArrayList<ArrayList<Integer> >(n + 1);
for (int j = 1; j <= n + 1; j++) {
ArrayList<Integer> list = new ArrayList<>();
aList.add(list);
}
for(int j = 0; j < n - 1; j ++) {
int u = s.nextInt();
int v = s.nextInt();
aList.get(u).add(v);
aList.get(v).add(u);
}
int[][][] dp = new int[n + 1][2][2];
for(int i = 0; i <= n; i++) {
for(int j = 0; j < 2; j++) dp[i][j] = null;
}
long ans1 = dfs1(aList, 1, 0, -1, dp)[0];
long ans2 = dfs1(aList, 1, 1, -1, dp)[0];
if(n == 2) ans1 = 2;
if(ans1 > ans2) {
output.write(ans1 + " " + dfs1(aList, 1, 0, -1, dp)[1] + "\n");
}
else if(ans1 < ans2) output.write(ans2 + " " + dfs1(aList, 1, 1, -1, dp)[1] + "\n");
else output.write(ans2 + " " + Math.min(dfs1(aList, 1, 0, -1, dp)[1], dfs1(aList, 1, 1, -1, dp)[1])+ "\n");
// for(int i = 1; i <= n; i++) {
// System.out.println(i + " " + dp[i][0] + " " + dp[i][1]);
// }
int[] arr = new int[n + 1];
dfs2(aList, 1, -1, 1, dp, arr);
//System.out.println(Arrays.toString(arr));
int[] ans = new int[n + 1];
for(int i = 1; i <= n; i++) {
if(arr[i] == 0) {
ans[i] = 1;
}
else {
ans[i] = aList.get(i).size();
}
}
for(int i = 1; i <= n; i++) output.write(ans[i] + " ");
output.write("\n");
}
output.flush();
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | b4667a2871e4e9a1a642b372323edbb8 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
Just have Patience + 1...
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
static class Pair implements Comparable<Pair> {
int goodVertices;
int sumOfWeights;
Pair(int goodVertices, int sumOfWeights) {
this.goodVertices = goodVertices;
this.sumOfWeights = sumOfWeights;
}
public int compareTo(Pair p) {
if (goodVertices == p.goodVertices) {
return Integer.compare(sumOfWeights, p.sumOfWeights);
}
return Integer.compare(p.goodVertices, goodVertices);
}
}
static int MAX = 200005;
static Map<Integer, List<Integer>> graph = new HashMap<>();
static int[] parent = new int[MAX];
static boolean[] visited = new boolean[MAX];
static boolean[] isGood = new boolean[MAX];
static Pair[][] dp = new Pair[MAX][2];
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 1; t <= test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
graph.put(i, new ArrayList<>());
}
for (int i = 0; i < n - 1; i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
graph.get(u).add(v);
graph.get(v).add(u);
}
if (n == 2) {
out.println(2 + " " + 2);
out.println(1 + " " + 1);
return;
}
parent[0] = -1;
dfs(0);
for (int i = 0; i < n; i++) {
dp[i][0] = dp[i][1] = new Pair(-1, -1);
}
Pair bestPair = getBest(dfs2(0, 0), dfs2(0, 1));
out.println(bestPair.goodVertices + " " + bestPair.sumOfWeights);
build(bestPair, 0);
for (int i = 0; i < n; i++) {
if (isGood[i]) {
out.print(graph.get(i).size() + " ");
}else {
out.print(1 + " ");
}
}
out.println();
}
private static void build(Pair bestPair, int currNode) {
Pair pair = dp[currNode][0];//dfs2(currNode, 0);
if (pair.goodVertices == bestPair.goodVertices && pair.sumOfWeights == bestPair.sumOfWeights) {
isGood[currNode] = false;
for (int adj : graph.get(currNode)) {
if (adj == parent[currNode]) {
continue;
}
build(getBest(dp[adj][0], dp[adj][1]), adj);
}
}else {
isGood[currNode] = true;
for (int adj : graph.get(currNode)) {
if (adj == parent[currNode]) {
continue;
}
build(dp[adj][0], adj);
}
}
}
private static Pair getBest(Pair p1, Pair p2) {
if (p1.goodVertices == p2.goodVertices) {
if (p1.sumOfWeights < p2.sumOfWeights) {
return p1;
}
return p2;
}
if (p1.goodVertices > p2.goodVertices) {
return p1;
}
return p2;
}
private static Pair dfs2(int currNode, int good) {
Pair currPair = dp[currNode][good];
if (currPair.goodVertices >= 0) {
return currPair;
}
currPair = new Pair(good, good == 1 ? graph.get(currNode).size() : 1);
for (int adjacentNode : graph.get(currNode)) {
if (adjacentNode == parent[currNode]) {
continue;
}
Pair nextPair = dfs2(adjacentNode, 0);
if (good == 0) {
nextPair = getBest(nextPair, dfs2(adjacentNode, 1));
}
currPair.goodVertices += nextPair.goodVertices;
currPair.sumOfWeights += nextPair.sumOfWeights;
}
return dp[currNode][good] = currPair;
}
private static void dfs(int currNode) {
visited[currNode] = true;
for (int adjacentNode : graph.get(currNode)) {
if (!visited[adjacentNode]) {
parent[adjacentNode] = currNode;
dfs(adjacentNode);
}
}
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 3e01923c33064a88f84eaa842da7944c | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class C774D {
static StringBuffer ans1 = new StringBuffer("");
static FastScanner sc = new FastScanner();
static PrintWriter printWriter = new PrintWriter(System.out);
/*
0. max count of good node if i is good
1. min sum if i is good
2. max count of good node if i is bad
3. min sum if i is bad
*/
static int[][] dp;
static int[] weight;
static Map<Integer, Set<Integer>> map = new HashMap<>();
public static void solve(int n, int[][] edges) {
if(n == 2){
printWriter.println("2 2");
printWriter.println("1 1");
return;
}
init(edges);
dp = new int[n + 1][4];
weight = new int[n];
helper(1, -1);
helper2(1, -1, false);
if(dp[1][2] > dp[1][0] || (dp[1][2] == dp[1][0] && dp[1][3] <= dp[1][1])) {
printWriter.println(dp[1][2] + " " + dp[1][3]);
} else {
printWriter.println(dp[1][0] + " " + dp[1][1]);
}
for(int w: weight) {
printWriter.print(w + " ");
}
}
public static void init(int[][] edges) {
for(int[] edge: edges) {
Set<Integer> set = map.getOrDefault(edge[0], new HashSet<>());
set.add(edge[1]);
map.put(edge[0], set);
Set<Integer> set1 = map.getOrDefault(edge[1], new HashSet<>());
set1.add(edge[0]);
map.put(edge[1], set1);
}
}
public static void helper(int i, int prev) {
if(map.get(i).size() == 1 && map.get(i).contains(prev)) {
dp[i] = new int[]{1, 1, 0, 1};
return;
}
int[] res = new int[4];
res[0] = 1;
res[1] = map.get(i).size();
res[3] = 1;
for(int next: map.get(i)) {
if(next == prev) continue;
helper(next, i);
int[] t = dp[next];
res[0] += t[2];
res[1] += t[3];
if(t[0] < t[2]) {
res[2] += t[2];
res[3] += t[3];
} else if(t[0] > t[2]){
res[2] += t[0];
res[3] += t[1];
} else {
res[2] += t[0];
res[3] += Math.min(t[1], t[3]);
}
}
dp[i] = res;
}
public static void helper2(int i, int prev, boolean isPrevGood) {
int[] t = dp[i];
boolean isGood;
if(isPrevGood || t[2] > t[0] || (t[2] == t[0] && t[3] <= t[1])) {
weight[i - 1] = 1;
isGood = false;
} else {
weight[i - 1] = map.get(i).size();
isGood = true;
}
for(int next: map.get(i)) {
if(next == prev) continue;
helper2(next, i, isGood);
}
}
public static void main(String[] args) {
int n = sc.nextInt();
int[][] edges = new int[n - 1][2];
for (int i = 0; i < n - 1; i++) {
edges[i][0] = sc.nextInt();
edges[i][1] = sc.nextInt();
}
solve(n, edges);
printWriter.flush();
}
/*****************************************************************
******************** DO NOT READ AFTER THIS LINE *****************
*****************************************************************/
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] read2dArray(int n, int m) {
int arr[][] = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = nextInt();
}
}
return arr;
}
ArrayList<Integer> readArrayList(int n) {
ArrayList<Integer> arr = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
int a = nextInt();
arr.add(a);
}
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 531609d9f91fbbb5512f1704b144ec13 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.*;
import java.util.*;
public class WeightTheTree {
public static void solve(FastIO io) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 1; i < N; ++i) {
final int U = io.nextInt();
final int V = io.nextInt();
nodes[U].next.add(nodes[V]);
nodes[V].next.add(nodes[U]);
}
if (N == 2) {
io.println(2, 2);
io.println(1, 1);
return;
}
nodes[1].root(null);
MemoData[][] memo = new MemoData[2][N + 1];
MemoData happyResult = get(HAPPY, nodes[1], memo);
MemoData unhappyResult = get(UNHAPPY, nodes[1], memo);
MemoData result = betterResult(happyResult, unhappyResult);
boolean[] markHappy = new boolean[N + 1];
if (result == happyResult) {
mark(HAPPY, nodes[1], memo, markHappy);
} else {
mark(UNHAPPY, nodes[1], memo, markHappy);
}
int goodCount = 0;
int weightSum = 0;
int[] nodeValues = new int[N + 1];
for (int i = 1; i <= N; ++i) {
if (markHappy[i]) {
++goodCount;
nodeValues[i] = nodes[i].next.size();
if (nodes[i].parent != null) {
++nodeValues[i];
}
} else {
nodeValues[i] = 1;
}
weightSum += nodeValues[i];
}
io.println(goodCount, weightSum);
io.printlnArray(Arrays.copyOfRange(nodeValues, 1, N + 1));
}
private static final int UNHAPPY = 0;
private static final int HAPPY = 1;
private static MemoData get(int isHappy, Node u, MemoData[][] memo) {
if (memo[isHappy][u.id] == null) {
if (isHappy == HAPPY) {
int maxHappiness = 1;
int minWeight = u.next.size();
if (u.parent != null) {
++minWeight;
}
for (Node v : u.next) {
MemoData result = get(UNHAPPY, v, memo);
maxHappiness += result.maxHappiness;
minWeight += result.minWeight;
}
memo[isHappy][u.id] = new MemoData(maxHappiness, minWeight);
} else {
int maxHappiness = 0;
int minWeight = 1;
for (Node v : u.next) {
MemoData happyResult = get(HAPPY, v, memo);
MemoData unhappyResult = get(UNHAPPY, v, memo);
MemoData result = betterResult(happyResult, unhappyResult);
maxHappiness += result.maxHappiness;
minWeight += result.minWeight;
}
memo[isHappy][u.id] = new MemoData(maxHappiness, minWeight);
}
}
return memo[isHappy][u.id];
}
private static void mark(int isHappy, Node u, MemoData[][] memo, boolean[] outHappy) {
if (isHappy == HAPPY) {
outHappy[u.id] = true;
for (Node v : u.next) {
mark(UNHAPPY, v, memo, outHappy);
}
} else {
for (Node v : u.next) {
MemoData happyResult = get(HAPPY, v, memo);
MemoData unhappyResult = get(UNHAPPY, v, memo);
MemoData result = betterResult(happyResult, unhappyResult);
if (result == happyResult) {
mark(HAPPY, v, memo, outHappy);
} else {
mark(UNHAPPY, v, memo, outHappy);
}
}
}
}
private static MemoData betterResult(MemoData a, MemoData b) {
if (a.maxHappiness > b.maxHappiness) {
return a;
} else if (a.maxHappiness < b.maxHappiness) {
return b;
} else if (a.minWeight < b.minWeight) {
return a;
} else {
return b;
}
}
private static class MemoData {
public int maxHappiness;
public int minWeight;
public MemoData(int maxHappiness, int minWeight) {
this.maxHappiness = maxHappiness;
this.minWeight = minWeight;
}
}
private static class Node {
public int id;
public ArrayList<Node> next = new ArrayList<>();
public Node parent;
public Node(int id) {
this.id = id;
}
public void root(Node p) {
next.remove(p);
parent = p;
for (Node v : next) {
v.root(this);
}
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | e629e0535f2e9e5c4713c45a5250935a | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.cert.X509CRL;
import java.util.*;
import java.lang.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
@SuppressWarnings("unused")
public class Main {
static InputStream is;
static PrintWriter out;
static String INPUT = "";
static String OUTPUT = "";
//global
private final static long BASE = 998244353L;
private final static int ALPHABET = (int)('z') - (int)('a') + 1;
//private final static int BASE = 1000000007;
private final static int INF_I = (1<<31)-1;
private final static long INF_L = (1l<<63)-1;
private final static int MAXN = 200100;
private final static int MAXK = 31;
private final static int[] DX = {-1,0,1,0};
private final static int[] DY = {0,1,0,-1};
private static List<List<Integer>> G = new ArrayList<>();
private static int[] ans;
private static int[][] F;
private static long[][] S;
private static int better(int u) {
boolean isFine = (F[u][0] > F[u][1] || (F[u][0]==F[u][1] && S[u][0] < S[u][1]));
if (isFine) return 0;
return 1;
}
private static void dfs(int u, int pa) {
F[u][0] = 0; S[u][0] = 1;
F[u][1] = 1; S[u][1] = G.get(u).size();
for (int v : G.get(u)) {
if (v==pa) continue;
dfs(v,u);
F[u][1] += F[v][0];
S[u][1] += S[v][0];
int k = better(v);
F[u][0] += F[v][k];
S[u][0] += S[v][k];
}
}
private static void dfs2(int u, int pa, int color) {
if (color == 0) ans[u] = 1;
else ans[u] = G.get(u).size();
for (int v : G.get(u)) {
if (v==pa) continue;
if (color==1) dfs2(v,u,0);
else dfs2(v,u,better(v));
}
}
static void solve() {
int ntest = 1;
for (int test=0;test<ntest;test++) {
int N = readInt();
if (N==2) {
out.println(2 + " " + 2);
out.println(1 + " " + 1);
continue;
}
for (int i=0;i<N;i++) G.add(new ArrayList<>());
F = new int[N][2];
S = new long[N][2];
ans = new int[N];
for (int i=0;i<N-1;i++) {
int u = readInt() - 1;
int v = readInt() - 1;
G.get(u).add(v);
G.get(v).add(u);
}
dfs(0, -1);
int k = better(0);
out.println(F[0][k] + " " + S[0][k]);
dfs2(0,-1,k);
for (int i=0;i<N;i++) out.print(ans[i] + " ");
}
}
public static void main(String[] args) throws Exception
{
long S = System.currentTimeMillis();
if (INPUT=="") {
is = System.in;
} else {
File file = new File(INPUT);
is = new FileInputStream(file);
}
if (OUTPUT == "") out = new PrintWriter(System.out);
else out = new PrintWriter(OUTPUT);
solve();
out.flush();
long G = System.currentTimeMillis();
}
private static class Point<T extends Number & Comparable<T>> implements Comparable<Point<T>> {
private T x;
private T y;
public Point(T x, T y) {
this.x = x;
this.y = y;
}
public T getX() {return x;}
public T getY() {return y;}
@Override
public int compareTo(Point<T> o) {
int cmp = x.compareTo(o.getX());
if (cmp==0) return y.compareTo(o.getY());
return cmp;
}
}
private static class ClassComparator<T extends Comparable<T>> implements Comparator<T> {
public ClassComparator() {}
@Override
public int compare(T a, T b) {
return a.compareTo(b);
}
}
private static class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> {
public ListComparator() {}
@Override
public int compare(List<T> o1, List<T> o2) {
for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) {
int c = o1.get(i).compareTo(o2.get(i));
if (c != 0) {
return c;
}
}
return Integer.compare(o1.size(), o2.size());
}
}
private static boolean eof()
{
if(lenbuf == -1)return true;
int lptr = ptrbuf;
while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;
try {
is.mark(1000);
while(true){
int b = is.read();
if(b == -1){
is.reset();
return true;
}else if(!isSpaceChar(b)){
is.reset();
return false;
}
}
} catch (IOException e) {
return true;
}
}
private static byte[] inbuf = new byte[1024];
static int lenbuf = 0, ptrbuf = 0;
private static int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
// private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); }
private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private static double readDouble() { return Double.parseDouble(readString()); }
private static char readChar() { return (char)skip(); }
private static String readString()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private static char[] readChar(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private static char[][] readTable(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = readChar(m);
return map;
}
private static int[] readIntArray(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = readInt();
return a;
}
private static long[] readLongArray(int n) {
long[] a = new long[n];
for (int i=0;i<n;i++) a[i] = readLong();
return a;
}
private static int readInt()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static long readLong()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 3dc2af4b07061d009e492ebf36f1771f | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main{
public static void main(String[]args){
long s = System.currentTimeMillis();
new Solver().run();
System.err.println(System.currentTimeMillis()-s+"ms");
}
}
class Ans{
int score, type, nodeNum;
long weightUsed;
public Ans(int score, int type, int nodeNum, long weightUsed){
this.type = type;
this.nodeNum = nodeNum;
this.score = score;
this.weightUsed = weightUsed;
}
static public Ans from(int s, int t, int n, long w){
return new Ans(s, t, n, w);
}
static public Ans better(Ans A, Ans B){
if(A.score != B.score){
return A.score > B.score ? A : B;
}
return A.weightUsed < B.weightUsed ? A : B;
}
}
class Solver{
final long mod = (long)1e9+7l;
final boolean DEBUG = true, MULTIPLE_TC = false;
FastReader sc;
PrintWriter out;
int N, res[];
ArrayList<Integer> adj[];
ArrayList<Ans> adjForRebuild[][];
Ans dp[][];
void addEdge(int u, int v){
adj[u].add(v);
adj[v].add(u);
}
void init(){
N = ni();
adj = new ArrayList[N + 1];
adjForRebuild = new ArrayList[N + 1][2];
dp = new Ans[N + 1][2];
res = new int[N + 1];
for(int i = 0; i <= N; i++){
for(int j = 0; j < 2; j++){
dp[i][j] = Ans.from(0, j, i, 0l);
}
}
for(int i = 0; i <= N; i++){
adj[i] = new ArrayList<>();
}
for(int i = 0; i <= N; i++){
for(int j = 0; j < 2; j++){
adjForRebuild[i][j] = new ArrayList<>();
}
}
for(int i = 1; i < N; i++){
int u = ni(), v = ni();
addEdge(u, v);
}
}
void f(int node, int par){
dp[node][1].weightUsed += adj[node].size() * 1l;
dp[node][1].score += 1;
dp[node][0].weightUsed = 1l;
for(int kid : adj[node]){
if(kid == par){
continue;
}
f(kid, node);
// type curr node
dp[node][1].weightUsed += dp[kid][0].weightUsed;
dp[node][1].score += dp[kid][0].score;
adjForRebuild[node][1].add(dp[kid][0]);
// do not type curr node
Ans take = Ans.better(dp[kid][0], dp[kid][1]);
dp[node][0].weightUsed += take.weightUsed;
dp[node][0].score += take.score;
adjForRebuild[node][0].add(take);
}
}
void rebuildTree(Ans node, int par){
int type = node.type, nodeNum = node.nodeNum;
if(type == 0){
res[nodeNum] = 1;
}else{
res[nodeNum] = adj[nodeNum].size();
}
for(Ans ans : adjForRebuild[nodeNum][type]){
if(ans.nodeNum == par){
continue;
}
rebuildTree(ans, nodeNum);
}
}
void process(int testNumber){
init();
if(N == 2){
p("2 2\n1 1"); return;
}
f(1, 0);
Ans take = Ans.better(dp[1][0], dp[1][1]);
rebuildTree(take, 0);
pn(take.score + " " + take.weightUsed);
for(int i = 1; i <= N; i++){
p(res[i] + " ");
}
p("\n");
}
void run(){
sc = new FastReader();
out = new PrintWriter(System.out);
int t = MULTIPLE_TC ? ni() : 1;
for(int test = 1; test <= t; test++){
process(test);
}
out.flush();
}
void trace(Object... o){ if(!DEBUG) return; System.err.println(Arrays.deepToString(o)); };
void pn(Object o){ out.println(o); }
void p(Object o){ out.print(o); }
int ni(){ return Integer.parseInt(sc.next()); }
long nl(){ return Long.parseLong(sc.next()); }
double nd(){ return Double.parseDouble(sc.next()); }
String nln(){ return sc.nextLine(); }
long gcd(long a, long b){ return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){ return (b==0)?a:gcd(b,a%b); }
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); }
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); }
return str;
}
}
}
class pair implements Comparable<pair> {
int first, second;
public pair(int first, int second){
this.first = first;
this.second = second;
}
@Override
public int compareTo(pair ob){
if(this.first != ob.first)
return this.first - ob.first;
return this.second - ob.second;
}
@Override
public String toString(){
return this.first + " " + this.second;
}
static public pair from(int f, int s){
return new pair(f, s);
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 428558308c14c53eb7983b0fdb132c13 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.lang.Math;
import java.nio.BufferOverflowException;
import java.util.*;
import java.io.*;
import java.lang.Math;
public final class code {
static int globalCnt = 0;
static int loss = 0;
/*
* static class sortCond implements Comparator<Pair<Integer, Integer>> {
*
* @Override
* public int compare(Pair<Integer, Integer> obj, Pair<Integer, Integer> obj1) {
* if (obj.getValue() < obj1.getValue()) {
* return -1;
* } else {
* return 1;
* }
* }
* }
*/
static class Pair {
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
int getKey() {
return this.a;
}
int getValue() {
return this.b;
}
}
/*
* static class Pair<f, s> {
* f a;
* s b;
*
* Pair(f a, s b) {
* this.a = a;
* this.b = b;
* }
*
* f getKey() {
* return this.a;
* }
*
* s getValue() {
* return this.b;
* }
*
* }
*/
interface modOperations {
long mod(long a, long b, long mod);
}
static long findBinaryExponentian(long a, long pow, long mod) {
if (pow == 1) {
return a;
} else if (pow == 0) {
return 1;
} else {
long retVal = findBinaryExponentian(a, (int) pow / 2, mod);
return modMul.mod(modMul.mod(retVal, retVal, mod), (pow % 2 == 0) ? 1 : a, mod);
}
}
static long findPow(long a, int b) {
if (b == 1) {
return a;
} else if (b == 0) {
return 1L;
} else {
long res = findPow(a, (int) b / 2);
return res * res * (b % 2 == 1 ? a : 1);
}
}
static int bleft(int ele, ArrayList<Integer> sortedArr) {
int l = 0;
int h = sortedArr.size() - 1;
int ans = -1;
while (l <= h) {
int mid = l + (int) (h - l) / 2;
if (sortedArr.get(mid) < ele) {
l = mid + 1;
} else if (sortedArr.get(mid) >= ele) {
ans = mid;
h = mid - 1;
}
}
return ans;
}
static long gcd(long a, long b) {
long div = b;
long rem = a % b;
while (rem != 0) {
long temp = rem;
rem = div % rem;
div = temp;
}
return div;
}
static int log(long no) {
int i = 0;
while ((1 << i) <= no) {
i += 1;
}
return i - 1;
}
static modOperations modAdd = (long a, long b, long mod) -> {
return (a % mod + b % mod) % mod;
};
static modOperations modSub = (long a, long b, long mod) -> {
return (a % mod - b % mod + mod) % mod;
};
static modOperations modMul = (long a, long b, long mod) -> {
return (a % mod * b % mod) % mod;
};
static modOperations modDiv = (long a, long b, long mod) -> {
return modMul.mod(a, findBinaryExponentian(b, mod - 1, mod), mod);
};
static ArrayList<Integer> primeList(int MAXI) {
int[] prime = new int[MAXI + 1];
ArrayList<Integer> obj = new ArrayList<Integer>();
for (int i = 2; i <= (int) Math.sqrt(MAXI) + 1; i++) {
if (prime[i] == 0) {
obj.add(i);
for (int j = i * i; j <= MAXI; j += i) {
prime[j] = 1;
}
}
}
for (int i = (int) Math.sqrt(MAXI) + 1; i <= MAXI; i++) {
if (prime[i] == 0) {
obj.add(i);
}
}
return obj;
}
static int arrSum(int[] arr) {
int tot = 0;
for (int i = 0; i < arr.length; i++) {
tot += arr[i];
}
return tot;
}
static void dptraversal(ArrayList<ArrayList<Integer>> tree, Pair[] good, Pair[] nGood, int root, int par) {
int ninc = 0, nchild = 0, inc = 0, child = 0;
for (int i = 0; i < tree.get(root).size(); i++) {
if (tree.get(root).get(i) != par) {
dptraversal(tree, good, nGood, tree.get(root).get(i), root);
inc += nGood[tree.get(root).get(i)].getValue();
child += nGood[tree.get(root).get(i)].getKey();
if (nGood[tree.get(root).get(i)].getKey() > good[tree.get(root).get(i)].getKey()) {
nchild += nGood[tree.get(root).get(i)].getKey();
ninc += nGood[tree.get(root).get(i)].getValue();
} else if (nGood[tree.get(root).get(i)].getKey() < good[tree.get(root).get(i)].getKey()){
nchild += good[tree.get(root).get(i)].getKey();
ninc += good[tree.get(root).get(i)].getValue();
}else{
if(nGood[tree.get(root).get(i)].getValue() <= good[tree.get(root).get(i)].getValue()){
nchild += nGood[tree.get(root).get(i)].getKey();
ninc += nGood[tree.get(root).get(i)].getValue();
}else{
nchild += good[tree.get(root).get(i)].getKey();
ninc += good[tree.get(root).get(i)].getValue();
}
}
}
}
good[root] = new Pair(child + 1, inc + tree.get(root).size() + (par == -1 ? 0 : 1));
nGood[root] = new Pair(nchild, ninc + 1);
}
static void assignment(ArrayList<ArrayList<Integer>> tree, boolean isBad, int g[], Pair[] good, Pair[] nGood,
int root, int par) {
boolean isSat = true;
if (isBad) {
isSat = false;
} else if (good[root].getKey() < nGood[root].getKey()) {
isSat = false;
} else if (good[root].getKey() == nGood[root].getKey() && good[root].getValue() >= nGood[root].getValue()) {
isSat = false;
} else {
g[root] = 1;
}
for (int i = 0; i < tree.get(root).size(); i++) {
if (tree.get(root).get(i) != par) {
assignment(tree, isSat, g, good, nGood, tree.get(root).get(i), root);
}
}
}
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine()), i, u, v, cnt = 0, sum = 0;
ArrayList<ArrayList<Integer>> tree = new ArrayList<>();
for (i = 0; i < n; i++) {
tree.add(new ArrayList<>());
}
for (i = 0; i < n - 1; i++) {
String a[] = br.readLine().split(" ");
u = Integer.parseInt(a[0]);
v = Integer.parseInt(a[1]);
tree.get(u - 1).add(v - 1);
tree.get(v - 1).add(u - 1);
}
if (n == 2) {
System.out.println(2 + " " + 2);
System.out.println(1 + " " + 1);
} else {
Pair[] good = new Pair[n];
Pair[] nGood = new Pair[n];
int[] g = new int[n];
int aa[] = new int[n];
dptraversal(tree, good, nGood, 0, -1);
assignment(tree, false, g, good, nGood, 0, -1);
/*
* for (i = 0; i < n; i++) {
* System.out.println(i);
* System.out.println(good[i].getKey() + " " + good[i].getValue());
* System.out.println(nGood[i].getKey() + " " + nGood[i].getValue());
* }
*/
for (i = 0; i < n; i++) {
if (g[i] == 1) {
cnt++;
sum += tree.get(i).size();
aa[i] = tree.get(i).size();
} else {
sum += 1;
aa[i] = 1;
}
}
System.out.println(cnt + " " + sum);
for (i = 0; i < n; i++) {
System.out.print(aa[i] + " ");
}
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 4594d10ef9c126c4eba6254a95d40cae | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TreeSet;
public final class CF_774_D2_D
{
static boolean verb=true;
static void log(Object X){if (verb) System.err.println(X);}
static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}}
static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}}
static void logWln(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");}}
static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}}
static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}}
static void logWln(Object X){if (verb) System.err.print(X);}
static void info(Object o){ System.out.println(o);}
static void output(Object o){outputWln(""+o+"\n"); }
static void outputFlush(Object o){try {out.write(""+ o+"\n");out.flush();} catch (Exception e) {}}
static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}}
// Global vars
static BufferedWriter out;
static InputReader reader;
static void test() {
log("testing");
Random r=new Random();
int NTESTS=1000000;
int NMAX=22;
int VMAX=10;
for (int t=0;t<NTESTS;t++) {
}
log("testing done");
}
static class Composite implements Comparable<Composite>{
int v;
int idx;
public int compareTo(Composite X) {
if (v!=X.v)
return v-X.v;
return idx-X.idx;
}
public Composite(int v, int idx) {
this.v = v;
this.idx = idx;
}
}
static void dfs(ArrayList<Integer>[] friends) {
int n=friends.length;
if (n==2) {
output("2 2");
output("1 1");
return;
}
int[] anc=new int[n];
int[] w=new int[n];
int[] stack=new int[n];
int[] ptr=new int[n];
int[][] nb=new int[2][n];
int[][] cst =new int[2][n];
int[] hc=new int[n];
int st=0;
stack[st++]=0;
anc[0]=-1;
while (st>0) {
int u=stack[st-1];
//log("prcoessing u:"+u);
if (ptr[u]<friends[u].size()) {
int v=friends[u].get(ptr[u]++);
if (v!=anc[u]) {
anc[v]=u;
stack[st++]=v;
}
} else {
st--;
int child=0;
int mx0=0;
int mx1=1;
int cst0=1;
int cst1=0;
for (int v:friends[u]) {
if (v!=anc[u]) {
child++;
// first case of 0
mx0+=Math.max(nb[0][v], nb[1][v]);
if (nb[0][v]>nb[1][v]) {
cst0+=cst[0][v];
} else if (nb[0][v]<nb[1][v]) {
cst0+=cst[1][v];
} else {
cst0+=Math.min(cst[0][v],cst[1][v]);
}
mx1+=nb[0][v];
cst1+=cst[0][v];
}
}
cst1+=friends[u].size();
nb[0][u]=mx0;
nb[1][u]=mx1;
cst[0][u]=cst0;
cst[1][u]=cst1;
//log("u:"+u+" child:"+child);
//log("u:"+(u+1)+" mx0:"+mx0+" mx1:"+mx1+" cst0:"+cst0+" cst1:"+cst1);
}
}
// now start reverse
//log(nb[0]);
//log(nb[1]);
int nbt=0;
int cstt=0;
int[] select=new int[n];
if (nb[0][0]>nb[1][0]) {
nbt=nb[0][0];
cstt=cst[0][0];
select[0]=0;
} else if (nb[0][0]<nb[1][0]) {
nbt=nb[1][0];
cstt=cst[1][0];
select[0]=1;
} else {
nbt=nb[0][0];
if (cst[0][0]<cst[1][0])
select[0]=0;
else
select[0]=1;
cstt=Math.min(cst[0][0],cst[1][0]);
}
//log(nbt+" "+cstt);
int[] h=new int[n];
stack[st++]=0;
while (st>0) {
int u=stack[--st];
//log("u:"+(u+1)+" select:"+select[u]);
if (select[u]==1) {
h[u]=friends[u].size();
for (int v:friends[u]) {
if (v!=anc[u]) {
select[v]=0;
stack[st++]=v;
}
}
} else {
h[u]=1;
for (int v:friends[u]) {
if (v!=anc[u]) {
stack[st++]=v;
if (nb[0][v]>nb[1][v]) {
select[v]=0;
} else if (nb[0][v]<nb[1][v]) {
select[v]=1;
} else {
if (cst[0][v]<=cst[1][v])
select[v]=0;
else
select[v]=1;
}
}
}
}
}
output(nbt+" "+cstt);
StringBuffer sb=new StringBuffer();
for (int x:h)
sb.append(x+" ");
output(sb);
}
static long mod=1000000007;
static int IRRE=1;
static int DEST=2;
static void process() throws Exception {
out = new BufferedWriter(new OutputStreamWriter(System.out));
reader = new InputReader(System.in);
int n=reader.readInt();
ArrayList<Integer>[] friends=new ArrayList[n];
for (int u=0;u<n;u++) {
friends[u]=new ArrayList<Integer>();
}
for (int i=0;i<n-1;i++) {
int u=reader.readInt()-1;
int v=reader.readInt()-1;
friends[u].add(v);
friends[v].add(u);
}
dfs(friends);
try {
out.close();
} catch (Exception Ex) {
}
}
public static void main(String[] args) throws Exception {
process();
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public final String readString() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public final String readString(int L) throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder(L);
do {
res.append((char) c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public final int readInt() throws IOException {
int c = read();
boolean neg = false;
while (isSpaceChar(c)) {
c = read();
}
char d = (char) c;
// log("d:"+d);
if (d == '-') {
neg = true;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
// log("res:"+res);
if (neg)
return -res;
return res;
}
public final long readLong() throws IOException {
int c = read();
boolean neg = false;
while (isSpaceChar(c)) {
c = read();
}
char d = (char) c;
// log("d:"+d);
if (d == '-') {
neg = true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
// log("res:"+res);
if (neg)
return -res;
return res;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
/*
1
10
1 0 0 0 0 1 0 0 1 1
1
12
1 0 0 1 0 0 1 0 0 0 0 1
1
12
1 0 0 1 0 0 1 0 0 0 0 1
3
12
1 0 0 1 0 0 1 0 0 0 0 1
10
1 0 0 0 0 1 0 0 1 1
12
1 0 0 1 0 0 1 0 0 0 0 1
1
11
1 0 0 0 0 0 0 0 1 1 1
19
1 1 0 1 1 1 1 1 1 0 1 0 0 0 0 1 0 1 1
19
1 0 0 1 1 0 0 1 1 0 0 0 1 1 0 0 0 1 0
19
1 0 0 0 1 1 0 0 1 1 0 0 0 1 1 0 0 1 0
1
20
1 1 0 0 0 1 0 1 1 1 0 1 1 1 1 1 0 0 1 0
*/ | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | bcc8bd69829060b9e0b6c97dfdb4ff21 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.util.*;
import java.io.*;
public class _1646_D {
static int n;
static ArrayList<Integer>[] tree;
static int[][][] dp;
static int[] res;
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(in.readLine());
tree = new ArrayList[n];
for(int i = 0; i < n; i++) {
tree[i] = new ArrayList<Integer>();
}
for(int i = 0; i < n - 1; i++) {
StringTokenizer line = new StringTokenizer(in.readLine());
int v1 = Integer.parseInt(line.nextToken()) - 1;
int v2 = Integer.parseInt(line.nextToken()) - 1;
tree[v1].add(v2);
tree[v2].add(v1);
}
if(n == 2) {
out.println("2 2");
out.println("1 1");
}else {
dp = new int[n][2][2];
dfs(0, -1);
int best = 0;
if(dp[0][1][0] > dp[0][0][0] || (dp[0][1][0] == dp[0][0][0] && dp[0][1][1] < dp[0][0][1])) {
best = 1;
}
res = new int[n];
dfs2(0, -1, best);
out.println(dp[0][best][0] + " " + dp[0][best][1]);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n; i++) {
sb.append(res[i]);
sb.append(' ');
}
out.println(sb.toString());
}
in.close();
out.close();
}
static void dfs(int node, int prev) {
for(int nei : tree[node]) {
if(nei != prev) {
dfs(nei, node);
int count = dp[nei][0][0];
int sum = dp[nei][0][1];
if(dp[nei][1][0] > count || (dp[nei][1][0] == count && dp[nei][1][1] < sum)) {
count = dp[nei][1][0];
sum = dp[nei][1][1];
}
dp[node][0][0] += count;
dp[node][0][1] += sum;
dp[node][1][0] += dp[nei][0][0];
dp[node][1][1] += dp[nei][0][1];
}
}
dp[node][0][1]++;
dp[node][1][0]++;
dp[node][1][1] += tree[node].size();
}
static void dfs2(int node, int prev, int use) {
if(use == 0) {
res[node] = 1;
}else {
res[node] = tree[node].size();
}
for(int nei : tree[node]) {
if(nei != prev) {
if(use == 1) {
dfs2(nei, node, 0);
}else {
int best = 0;
if(dp[nei][1][0] > dp[nei][0][0] || (dp[nei][1][0] == dp[nei][0][0] && dp[nei][1][1] < dp[nei][0][1])) {
best = 1;
}
dfs2(nei, node, best);
}
}
}
}
}
| Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | e54131ca9f93873c8756da8c508bd8ce | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | /*
"Everything in the universe is balanced. Every disappointment
you face in life will be balanced by something good for you!
Keep going, never give up."
Just have Patience + 1...
*/
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution {
static class Pair implements Comparable<Pair> {
int goodVertices;
int sumOfWeights;
Pair(int goodVertices, int sumOfWeights) {
this.goodVertices = goodVertices;
this.sumOfWeights = sumOfWeights;
}
public int compareTo(Pair p) {
if (goodVertices == p.goodVertices) {
return Integer.compare(sumOfWeights, p.sumOfWeights);
}
return Integer.compare(p.goodVertices, goodVertices);
}
}
static int MAX = 200005;
static Map<Integer, List<Integer>> graph = new HashMap<>();
static int[] parent = new int[MAX];
static boolean[] visited = new boolean[MAX];
static boolean[] isGood = new boolean[MAX]; // isGood[i] is true if ith node is a good node.
// dp[i][0] is the maximum good nodes in the subtree of node i, such that ith node is not good.
// dp[i][1] is the maximum good nodes in the subtree of node i, such that ith node is good.
static Pair[][] dp = new Pair[MAX][2];
public static void main(String[] args) throws java.lang.Exception {
out = new PrintWriter(new BufferedOutputStream(System.out));
sc = new FastReader();
int test = 1;
for (int t = 1; t <= test; t++) {
solve();
}
out.close();
}
private static void solve() {
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
graph.put(i, new ArrayList<>());
}
for (int i = 0; i < n - 1; i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
graph.get(u).add(v);
graph.get(v).add(u);
}
if (n == 2) {
out.println(2 + " " + 2);
out.println(1 + " " + 1);
return;
}
parent[0] = -1;
findParentNodes(0);
for (int i = 0; i < n; i++) {
dp[i][0] = dp[i][1] = new Pair(-1, -1);
}
Pair bestWeightedTree = getBestPair(weightTheTree(0, 0), weightTheTree(0, 1));
out.println(bestWeightedTree.goodVertices + " " + bestWeightedTree.sumOfWeights);
findAllGoodNodesInWeightTree(bestWeightedTree, 0);
for (int i = 0; i < n; i++) {
if (isGood[i]) {
out.print(graph.get(i).size() + " ");
}else {
out.print(1 + " ");
}
}
out.println();
}
private static void findAllGoodNodesInWeightTree(Pair bestWeightedTree, int currNode) {
Pair currPair = dp[currNode][0];
if (equals(currPair, bestWeightedTree)) {
isGood[currNode] = false;
for (int adjacentNode : graph.get(currNode)) {
if (adjacentNode == parent[currNode]) {
continue;
}
findAllGoodNodesInWeightTree(getBestPair(dp[adjacentNode][0], dp[adjacentNode][1]), adjacentNode);
}
}else {
isGood[currNode] = true;
for (int adjacentNode : graph.get(currNode)) {
if (adjacentNode == parent[currNode]) {
continue;
}
findAllGoodNodesInWeightTree(dp[adjacentNode][0], adjacentNode);
}
}
}
private static boolean equals(Pair currPair, Pair bestWeightedTree) {
return currPair.goodVertices == bestWeightedTree.goodVertices && currPair.sumOfWeights == bestWeightedTree.sumOfWeights;
}
private static Pair getBestPair(Pair p1, Pair p2) {
if (p1.goodVertices == p2.goodVertices) {
if (p1.sumOfWeights < p2.sumOfWeights) {
return p1;
}
return p2;
}
if (p1.goodVertices > p2.goodVertices) {
return p1;
}
return p2;
}
private static Pair weightTheTree(int currNode, int good) {
Pair currPair = dp[currNode][good];
if (currPair.goodVertices >= 0) {
return currPair;
}
currPair = new Pair(good, good == 1 ? graph.get(currNode).size() : 1);
for (int adjacentNode : graph.get(currNode)) {
if (adjacentNode == parent[currNode]) {
continue;
}
Pair nextPair = weightTheTree(adjacentNode, 0);
if (good == 0) {
nextPair = getBestPair(nextPair, weightTheTree(adjacentNode, 1));
}
currPair.goodVertices += nextPair.goodVertices;
currPair.sumOfWeights += nextPair.sumOfWeights;
}
return dp[currNode][good] = currPair;
}
private static void findParentNodes(int currNode) {
visited[currNode] = true;
for (int adjacentNode : graph.get(currNode)) {
if (!visited[adjacentNode]) {
parent[adjacentNode] = currNode;
findParentNodes(adjacentNode);
}
}
}
public static FastReader sc;
public static PrintWriter out;
static class FastReader
{
BufferedReader br;
StringTokenizer str;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (str == null || !str.hasMoreElements())
{
try
{
str = new StringTokenizer(br.readLine());
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
}
return str.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException lastMonthOfVacation)
{
lastMonthOfVacation.printStackTrace();
}
return str;
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 11 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 5e97d96ab1301f81f4ca3d036968e879 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.*;
import java.util.*;
public class WeightTheTree {
public static void solve(FastIO io) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 1; i < N; ++i) {
final int U = io.nextInt();
final int V = io.nextInt();
nodes[U].next.add(nodes[V]);
nodes[V].next.add(nodes[U]);
}
if (N == 2) {
io.println(2, 2);
io.println(1, 1);
return;
}
nodes[1].root(null);
MemoData[][] memo = new MemoData[2][N + 1];
MemoData happyResult = get(HAPPY, nodes[1], memo);
MemoData unhappyResult = get(UNHAPPY, nodes[1], memo);
MemoData result = betterResult(happyResult, unhappyResult);
boolean[] markHappy = new boolean[N + 1];
if (result == happyResult) {
mark(HAPPY, nodes[1], memo, markHappy);
} else {
mark(UNHAPPY, nodes[1], memo, markHappy);
}
int goodCount = 0;
int weightSum = 0;
int[] nodeValues = new int[N + 1];
for (int i = 1; i <= N; ++i) {
if (markHappy[i]) {
++goodCount;
nodeValues[i] = nodes[i].next.size();
if (nodes[i].parent != null) {
++nodeValues[i];
}
} else {
nodeValues[i] = 1;
}
weightSum += nodeValues[i];
}
io.println(goodCount, weightSum);
io.printlnArray(Arrays.copyOfRange(nodeValues, 1, N + 1));
}
private static final int UNHAPPY = 0;
private static final int HAPPY = 1;
private static MemoData get(int isHappy, Node u, MemoData[][] memo) {
if (memo[isHappy][u.id] == null) {
if (isHappy == HAPPY) {
int maxHappiness = 1;
int minWeight = u.next.size();
if (u.parent != null) {
++minWeight;
}
for (Node v : u.next) {
MemoData result = get(UNHAPPY, v, memo);
maxHappiness += result.maxHappiness;
minWeight += result.minWeight;
}
memo[isHappy][u.id] = new MemoData(maxHappiness, minWeight);
} else {
int maxHappiness = 0;
int minWeight = 1;
for (Node v : u.next) {
MemoData happyResult = get(HAPPY, v, memo);
MemoData unhappyResult = get(UNHAPPY, v, memo);
MemoData result = betterResult(happyResult, unhappyResult);
maxHappiness += result.maxHappiness;
minWeight += result.minWeight;
}
memo[isHappy][u.id] = new MemoData(maxHappiness, minWeight);
}
}
return memo[isHappy][u.id];
}
private static void mark(int isHappy, Node u, MemoData[][] memo, boolean[] outHappy) {
if (isHappy == HAPPY) {
outHappy[u.id] = true;
for (Node v : u.next) {
mark(UNHAPPY, v, memo, outHappy);
}
} else {
for (Node v : u.next) {
MemoData happyResult = get(HAPPY, v, memo);
MemoData unhappyResult = get(UNHAPPY, v, memo);
MemoData result = betterResult(happyResult, unhappyResult);
if (result == happyResult) {
mark(HAPPY, v, memo, outHappy);
} else {
mark(UNHAPPY, v, memo, outHappy);
}
}
}
}
private static MemoData betterResult(MemoData a, MemoData b) {
if (a.maxHappiness > b.maxHappiness) {
return a;
} else if (a.maxHappiness < b.maxHappiness) {
return b;
} else if (a.minWeight < b.minWeight) {
return a;
} else {
return b;
}
}
private static class MemoData {
public int maxHappiness;
public int minWeight;
public MemoData(int maxHappiness, int minWeight) {
this.maxHappiness = maxHappiness;
this.minWeight = minWeight;
}
}
private static class Node {
public int id;
public ArrayList<Node> next = new ArrayList<>();
public Node parent;
public Node(int id) {
this.id = id;
}
public void root(Node p) {
next.remove(p);
parent = p;
for (Node v : next) {
v.root(this);
}
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 72d996606534597ff6c7035b08b95c30 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.*;
import java.util.*;
public class WeightTheTree {
public static void solve(FastIO io) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 1; i < N; ++i) {
final int U = io.nextInt();
final int V = io.nextInt();
nodes[U].next.add(nodes[V]);
nodes[V].next.add(nodes[U]);
}
if (N == 2) {
io.println(2, 2);
io.println(1, 1);
return;
}
nodes[1].root(null);
MemoData[][] memo = new MemoData[2][N + 1];
MemoData happyResult = get(HAPPY, nodes[1], memo);
MemoData unhappyResult = get(UNHAPPY, nodes[1], memo);
MemoData result = betterResult(happyResult, unhappyResult);
boolean[] markHappy = new boolean[N + 1];
if (result == happyResult) {
mark(HAPPY, nodes[1], memo, markHappy);
} else {
mark(UNHAPPY, nodes[1], memo, markHappy);
}
int goodCount = 0;
int weightSum = 0;
int[] nodeValues = new int[N + 1];
for (int i = 1; i <= N; ++i) {
if (markHappy[i]) {
++goodCount;
nodeValues[i] = nodes[i].next.size();
if (nodes[i].parent != null) {
++nodeValues[i];
}
} else {
nodeValues[i] = 1;
}
weightSum += nodeValues[i];
}
io.println(goodCount, weightSum);
io.printlnArray(Arrays.copyOfRange(nodeValues, 1, N + 1));
}
private static final int UNHAPPY = 0;
private static final int HAPPY = 1;
private static MemoData get(int isHappy, Node u, MemoData[][] memo) {
if (memo[isHappy][u.id] == null) {
if (isHappy == HAPPY) {
int maxHappiness = 1;
int minWeight = u.next.size();
if (u.parent != null) {
++minWeight;
}
for (Node v : u.next) {
MemoData result = get(UNHAPPY, v, memo);
maxHappiness += result.maxHappiness;
minWeight += result.minWeight;
}
memo[isHappy][u.id] = new MemoData(maxHappiness, minWeight);
} else {
int maxHappiness = 0;
int minWeight = 1;
for (Node v : u.next) {
MemoData happyResult = get(HAPPY, v, memo);
MemoData unhappyResult = get(UNHAPPY, v, memo);
MemoData result = betterResult(happyResult, unhappyResult);
maxHappiness += result.maxHappiness;
minWeight += result.minWeight;
}
memo[isHappy][u.id] = new MemoData(maxHappiness, minWeight);
}
}
return memo[isHappy][u.id];
}
private static void mark(int isHappy, Node u, MemoData[][] memo, boolean[] outHappy) {
if (isHappy == HAPPY) {
outHappy[u.id] = true;
for (Node v : u.next) {
mark(UNHAPPY, v, memo, outHappy);
}
} else {
for (Node v : u.next) {
MemoData happyResult = get(HAPPY, v, memo);
MemoData unhappyResult = get(UNHAPPY, v, memo);
MemoData result = betterResult(happyResult, unhappyResult);
if (result == happyResult) {
mark(HAPPY, v, memo, outHappy);
} else {
mark(UNHAPPY, v, memo, outHappy);
}
}
}
}
private static MemoData betterResult(MemoData a, MemoData b) {
if (a.maxHappiness > b.maxHappiness) {
return a;
} else if (a.maxHappiness < b.maxHappiness) {
return b;
} else if (a.minWeight < b.minWeight) {
return a;
} else {
return b;
}
}
private static class MemoData {
public int maxHappiness;
public int minWeight;
public MemoData(int maxHappiness, int minWeight) {
this.maxHappiness = maxHappiness;
this.minWeight = minWeight;
}
}
private static class Node {
public int id;
public ArrayList<Node> next = new ArrayList<>();
public Node parent;
public Node(int id) {
this.id = id;
}
public void root(Node p) {
next.remove(p);
parent = p;
for (Node v : next) {
v.root(this);
}
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 39f15dc16322811813b33815f269eb43 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class WeightTheTree {
public static void solve(FastIO io) {
final int N = io.nextInt();
Node[] nodes = new Node[N + 1];
for (int i = 1; i <= N; ++i) {
nodes[i] = new Node(i);
}
for (int i = 1; i < N; ++i) {
final int U = io.nextInt();
final int V = io.nextInt();
nodes[U].next.add(nodes[V]);
nodes[V].next.add(nodes[U]);
}
if (N == 2) {
io.println(2, 2);
io.println(1, 1);
return;
}
root(nodes[1], null);
MemoData[][] memo = new MemoData[2][N + 1];
MemoData happyResult = get(HAPPY, nodes[1], memo);
MemoData unhappyResult = get(UNHAPPY, nodes[1], memo);
MemoData result = betterResult(happyResult, unhappyResult);
boolean[] markHappy = new boolean[N + 1];
if (result == happyResult) {
mark(HAPPY, nodes[1], memo, markHappy);
} else {
mark(UNHAPPY, nodes[1], memo, markHappy);
}
int goodCount = 0;
int weightSum = 0;
int[] nodeValues = new int[N + 1];
for (int i = 1; i <= N; ++i) {
if (markHappy[i]) {
++goodCount;
nodeValues[i] = nodes[i].next.size();
if (i > 1) {
++nodeValues[i];
}
} else {
nodeValues[i] = 1;
}
weightSum += nodeValues[i];
}
io.println(goodCount, weightSum);
io.printlnArray(Arrays.copyOfRange(nodeValues, 1, N + 1));
if (N > 0) {
return;
}
PriorityQueue<NodeValue> pq = new PriorityQueue<>(new Comparator<NodeValue>() {
@Override
public int compare(NodeValue a, NodeValue b) {
return Integer.compare(a.value, b.value);
}
});
TreeSet<NodeValue> ts = new TreeSet<>(new Comparator<NodeValue>() {
@Override
public int compare(NodeValue a, NodeValue b) {
int dv = Integer.compare(a.value, b.value);
if (dv != 0) {
return dv;
}
return Integer.compare(a.node.id, b.node.id);
}
});
int visited = 0;
int[] updates = new int[N + 1];
int[] values = new int[N + 1];
boolean[] fixed = new boolean[N + 1];
for (int i = 1; i <= N; ++i) {
if (nodes[i].next.size() == 1) {
values[i] = 1;
updates[i] = 1;
fixed[i] = true;
Node parent = nodes[i].next.get(0);
++updates[parent.id];
values[parent.id] = 1;
++visited;
if (!fixed[parent.id] && parent.next.size() > 1) {
// System.out.format(" - PRE offered: %d\n", parent.id);
pq.offer(new NodeValue(parent, values[parent.id]));
ts.add(new NodeValue(parent, values[parent.id]));
}
fixed[i] = true;
fixed[parent.id] = true;
}
}
int[] theoreticalGood = new int[N + 1];
Arrays.fill(theoreticalGood, 1);
for (int i = 1; i <= N; ++i) {
if (nodes[i].next.size() == 1) {
Node parent = nodes[i].next.get(0);
if (parent.next.size() > 1) {
theoreticalGood[parent.id] = 0;
}
}
}
int theoreticalGoodCount = 0;
for (int i = 1; i <= N; ++i) {
theoreticalGoodCount += theoreticalGood[i];
}
while (!ts.isEmpty()) {
NodeValue nv = ts.first();
ts.remove(nv);
Node u = nv.node;
fixed[u.id] = true;
for (Node v : u.next) {
if (!fixed[v.id]) {
NodeValue item = new NodeValue(v, values[v.id]);
ts.remove(item);
values[v.id] += values[u.id];
ts.add(new NodeValue(v, values[v.id]));
}
}
}
int good = 0;
for (int i = 1; i <= N; ++i) {
int neighborSum = 0;
for (Node v : nodes[i].next) {
neighborSum += values[v.id];
}
if (values[i] == neighborSum) {
++good;
}
}
long valueSum = 0;
for (int i = 1; i <= N; ++i) {
valueSum += values[i];
}
if (theoreticalGoodCount != good) {
System.out.format("FAIL: want good %d, got %d\n", theoreticalGoodCount, good);
}
io.println(good, valueSum);
io.printlnArray(Arrays.copyOfRange(values, 1, N + 1));
if (N > 0) {
return;
}
boolean[] queued = new boolean[N + 1];
while (!pq.isEmpty()) {
NodeValue nv = pq.poll();
System.out.format("working on: %d\n", nv.node.id);
for (Node v : nv.node.next) {
if (!fixed[v.id] && !queued[v.id] && updates[v.id] < v.next.size()) {
System.out.format(" propagating value = %d: %d -> %d\n", values[nv.node.id], nv.node.id, v.id);
++updates[nv.node.id];
++updates[v.id];
values[v.id] += values[nv.node.id];
queued[v.id] = true;
pq.offer(new NodeValue(v, values[v.id]));
}
}
if (1 + 1 == 2) {
continue;
}
++visited;
// if (updates[nv.node.id] != nv.node.next.size() - 1) {
// continue;
// }
// done[nv.node.id] = true;
// System.out.format("node: %d\n", nv.node.id);
Node parent = null;
for (Node v : nv.node.next) {
if (!fixed[v.id] && updates[v.id] < v.next.size()) {
// System.out.format(" * node %d has %d updates and %d neighbors\n", v.id, updates[v.id], v.next.size());
if (parent != null) {
System.out.println("FAIL!");
}
parent = v;
// break;
}
}
if (parent == null) {
continue;
}
// System.out.format(" parent of %d is %d\n", nv.node.id, parent.id);
++updates[nv.node.id];
++updates[parent.id];
values[parent.id] += values[nv.node.id];
if (updates[parent.id] == parent.next.size() - 1) {
// System.out.format(" - offered: %d\n", parent.id);
pq.offer(new NodeValue(parent, values[parent.id]));
}
}
if (visited != N) {
System.out.format("FAIL: visited %d of %d nodes\n", visited, N);
}
// int good = 0;
// for (int i = 1; i <= N; ++i) {
// int neighborSum = 0;
// for (Node v : nodes[i].next) {
// neighborSum += values[v.id];
// }
// if (values[i] == neighborSum) {
// ++good;
// }
// }
//
// long valueSum = 0;
// for (int i = 1; i <= N; ++i) {
// valueSum += values[i];
// }
//
// io.println(good, valueSum);
// io.printlnArray(Arrays.copyOfRange(values, 1, N + 1));
}
private static final int UNHAPPY = 0;
private static final int HAPPY = 1;
private static MemoData get(int isHappy, Node u, MemoData[][] memo) {
if (memo[isHappy][u.id] == null) {
if (isHappy == HAPPY) {
int maxHappiness = 1;
int minWeight = u.next.size();
if (u.id > 1) {
++minWeight;
}
for (Node v : u.next) {
MemoData result = get(UNHAPPY, v, memo);
maxHappiness += result.maxHappiness;
minWeight += result.minWeight;
}
memo[isHappy][u.id] = new MemoData(maxHappiness, minWeight);
} else {
int maxHappiness = 0;
int minWeight = 1;
for (Node v : u.next) {
MemoData happyResult = get(HAPPY, v, memo);
MemoData unhappyResult = get(UNHAPPY, v, memo);
MemoData result;
if (happyResult.maxHappiness > unhappyResult.maxHappiness) {
result = happyResult;
} else if (happyResult.maxHappiness < unhappyResult.maxHappiness) {
result = unhappyResult;
} else if (happyResult.minWeight < unhappyResult.minWeight) {
result = happyResult;
} else {
result = unhappyResult;
}
maxHappiness += result.maxHappiness;
minWeight += result.minWeight;
}
memo[isHappy][u.id] = new MemoData(maxHappiness, minWeight);
}
// System.out.format("get(%d, %d) = (%d, %d)\n", isHappy, u.id, memo[isHappy][u.id].maxHappiness, memo[isHappy][u.id].minWeight);
}
return memo[isHappy][u.id];
}
private static void mark(int isHappy, Node u, MemoData[][] memo, boolean[] outHappy) {
if (isHappy == HAPPY) {
outHappy[u.id] = true;
for (Node v : u.next) {
mark(UNHAPPY, v, memo, outHappy);
}
} else {
for (Node v : u.next) {
MemoData happyResult = get(HAPPY, v, memo);
MemoData unhappyResult = get(UNHAPPY, v, memo);
MemoData result = betterResult(happyResult, unhappyResult);
if (result == happyResult) {
mark(HAPPY, v, memo, outHappy);
} else {
mark(UNHAPPY, v, memo, outHappy);
}
}
}
}
private static MemoData betterResult(MemoData a, MemoData b) {
if (a.maxHappiness > b.maxHappiness) {
return a;
} else if (a.maxHappiness < b.maxHappiness) {
return b;
} else if (a.minWeight < b.minWeight) {
return a;
} else {
return b;
}
}
private static void root(Node u, Node p) {
u.next.remove(p);
for (Node v : u.next) {
root(v, u);
}
}
private static class MemoData {
public int maxHappiness;
public int minWeight;
public MemoData(int maxHappiness, int minWeight) {
this.maxHappiness = maxHappiness;
this.minWeight = minWeight;
}
}
private static class NodeValue {
public Node node;
public int value;
public NodeValue(Node node, int value) {
this.node = node;
this.value = value;
}
}
// private static int getValue(Node u, int[] values) {
// if (values[u.id] > 0) {
// return values[u.id];
// }
// }
private static class Node {
public int id;
public ArrayList<Node> next = new ArrayList<>();
public Node(int id) {
this.id = id;
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | b113426e14fdb4f9d4ef11a733461b49 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.stream.IntStream;
public class Main implements Runnable {
InputReader in = new InputReader();
OutputWriter out = new OutputWriter();
static int[][] adj;
static int[][] maximumGoodVerticesInSubtree;
static long[][] minimumSubtreeSum;
static int[] weight, weightIncluded;
public static void main(String[] args) {
new Thread(null, new Main(), "whatever", 1 << 26).start();
}
public void run() {
try {
in.getTokens();
int N = in.nextInt();
int[] from = new int[N-1];
int[] to = new int[N-1];
int[] occurrencesOfVertex = new int[N];
for(int i=0; i<N-1; i++) {
in.getTokens();
from[i] = in.nextInt()-1;
to[i] = in.nextInt()-1;
occurrencesOfVertex[from[i]]++;
occurrencesOfVertex[to[i]]++;
}
int cntLeaves=0;
for(int i=0; i<N; i++) {
cntLeaves += (occurrencesOfVertex[i] == 1 ? 1 : 0);
}
boolean isSkewedTree = false;
if(cntLeaves == 2) {
isSkewedTree = true;
}
adj = getAdjList(from, to, N);
maximumGoodVerticesInSubtree = new int[N][2];
minimumSubtreeSum = new long[N][2];
getMaxGoodVertices(N, 0, -1);
int maxGoodVertices = Math.max(maximumGoodVerticesInSubtree[0][0], maximumGoodVerticesInSubtree[0][1]);
int compare = Integer.compare(maximumGoodVerticesInSubtree[0][0], maximumGoodVerticesInSubtree[0][1]);
weight = new int[N];
if(compare > 0) {
assignWeightToVertices(N, 0, -1, true);
} else if(compare < 0) {
assignWeightToVertices(N, 0, -1, false);
} else {
if(minimumSubtreeSum[0][0] < minimumSubtreeSum[0][1]) {
assignWeightToVertices(N, 0, -1, true);
} else {
assignWeightToVertices(N, 0, -1, false);
}
}
if(N==2) {
maxGoodVertices = 2;
for(int i=0; i<N; i++) {
weight[i]=1;
}
}
int weightSum = 0;
for(int i=0; i<N; i++) {
weightSum += weight[i];
}
out.println(maxGoodVertices + " " + weightSum);
out.print(weight[0]);
for(int i=1; i<N; i++) {
out.print(" " + weight[i]);
out.flush();
}
out.println("");
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static long assignWeightToVertices(int N, int currentVertex, int parentVertex, boolean includeCurrentVertex) {
if(!includeCurrentVertex) {
weight[currentVertex]=1;
} else {
weight[currentVertex]= adj[currentVertex].length;
}
long subtreeWeightsSum = weight[currentVertex];
for(Integer adjVertex : adj[currentVertex]) {
if(adjVertex != parentVertex) {
if(includeCurrentVertex) {
subtreeWeightsSum += assignWeightToVertices(N, adjVertex, currentVertex, false);
continue;
}
if(maximumGoodVerticesInSubtree[adjVertex][0] > maximumGoodVerticesInSubtree[adjVertex][1]) {
subtreeWeightsSum += assignWeightToVertices(N, adjVertex, currentVertex, true);
} else if(maximumGoodVerticesInSubtree[adjVertex][0] < maximumGoodVerticesInSubtree[adjVertex][1]) {
subtreeWeightsSum += assignWeightToVertices(N, adjVertex, currentVertex, false);
} else {
if(minimumSubtreeSum[adjVertex][0] < minimumSubtreeSum[adjVertex][1]) {
subtreeWeightsSum += assignWeightToVertices(N, adjVertex, currentVertex, true);
} else {
subtreeWeightsSum += assignWeightToVertices(N, adjVertex, currentVertex, false);
}
}
}
}
return subtreeWeightsSum;
}
private static void getMaxGoodVertices(int N, int currentVertex, int parentVertex) {
maximumGoodVerticesInSubtree[currentVertex][0] = 1;
maximumGoodVerticesInSubtree[currentVertex][1] = 0;
minimumSubtreeSum[currentVertex][0] = adj[currentVertex].length;
minimumSubtreeSum[currentVertex][1] = 1;
for(int adjVertex : adj[currentVertex]) {
if(adjVertex != parentVertex) {
getMaxGoodVertices(N, adjVertex, currentVertex);
maximumGoodVerticesInSubtree[currentVertex][0] += maximumGoodVerticesInSubtree[adjVertex][1];
maximumGoodVerticesInSubtree[currentVertex][1] += Math.max(maximumGoodVerticesInSubtree[adjVertex][0], maximumGoodVerticesInSubtree[adjVertex][1]);
minimumSubtreeSum[currentVertex][0] += minimumSubtreeSum[adjVertex][1];
if(maximumGoodVerticesInSubtree[adjVertex][0] > maximumGoodVerticesInSubtree[adjVertex][1]) {
minimumSubtreeSum[currentVertex][1] += minimumSubtreeSum[adjVertex][0];
} else if(maximumGoodVerticesInSubtree[adjVertex][0] < maximumGoodVerticesInSubtree[adjVertex][1]) {
minimumSubtreeSum[currentVertex][1] += minimumSubtreeSum[adjVertex][1];
} else {
minimumSubtreeSum[currentVertex][1] += Math.min(minimumSubtreeSum[adjVertex][0], minimumSubtreeSum[adjVertex][1]);
}
}
}
}
private static int[][] getAdjList(int[] from, int[] to, int N) {
int[] adjSize = new int[N];
for(int i=0; i<N-1; i++) {
adjSize[from[i]]++;
adjSize[to[i]]++;
}
int[][] adj = new int[N][];
for(int i=0; i<N; i++) {
adj[i] = new int[adjSize[i]];
adjSize[i] = 0;
}
for(int i=0; i<N-1; i++) {
adj[from[i]][adjSize[from[i]]++] = to[i];
adj[to[i]][adjSize[to[i]]++] = from[i];
}
return adj;
}
}
class InputReader {
private BufferedReader in;
private String[] tokens;
private int positionOfNextTokenToRead;
public InputReader() {
in = new BufferedReader(new InputStreamReader(System.in));
// in = new BufferedReader(new FileReader("inputFile.extension"));
}
public void getTokens() throws IOException {
String nextLine = in.readLine().trim();
tokens = nextLine.split(" ");
positionOfNextTokenToRead = 0;
}
public String nextStr() {
return tokens[positionOfNextTokenToRead++];
}
public Integer nextInt() {
return Integer.parseInt(tokens[positionOfNextTokenToRead++]);
}
public Long nextLong() {
return Long.parseLong(tokens[positionOfNextTokenToRead++]);
}
public Double nextDouble() {
return Double.parseDouble(tokens[positionOfNextTokenToRead++]);
}
public String nextLine() throws IOException {
return in.readLine().trim();
}
}
class OutputWriter {
private PrintWriter out;
public OutputWriter() {
out = new PrintWriter(System.out, false);
// out = new PrintWriter("outputFile.extension");
}
public void print(Object line) {
out.print(line);
}
public void println(Object line) {
out.println(line);
}
public void flush() {
out.flush();
}
public void close() {
out.close();
}
}
| Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | c9bfce0ce9581411ebe761e2dd087a48 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | /*
Competitive Programming Template
*/
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1646D
{
static int[][] edges;
public static void main(String hi[]) throws Exception
{
FastScanner infile = new FastScanner();
int N = infile.nextInt();
if(N == 2)
{
System.out.println("2 2");
System.out.println("1 1");
return;
}
edges = new int[N][];
int[] input = new int[2*N-2];
int[] freq = new int[N];
for(int i=0; i < N-1; i++)
{
int a = infile.nextInt()-1;
int b = infile.nextInt()-1;
input[i<<1] = a;
input[(i<<1)+1] = b;
freq[a]++; freq[b]++;
}
for(int v=0; v < N; v++)
edges[v] = new int[freq[v]];
for(int i=1; i < 2*N-2; i+=2)
{
int a = input[i-1];
int b = input[i];
edges[a][--freq[a]] = b;
edges[b][--freq[b]] = a;
}
dp0 = new Node[N];
dp1 = new Node[N];
par0 = new ArrayDeque[N];
par1 = new ArrayDeque[N];
for(int i=0; i < N; i++)
{
par0[i] = new ArrayDeque<Integer>();
par1[i] = new ArrayDeque<Integer>();
}
dfs(0, -1);
int current = 0;
int tag = 0;
StringBuilder sb = new StringBuilder();
if(dp0[0].compareTo(dp1[0]) > 0)
{
tag = 1;
sb.append(dp1[0].cnt+" "+dp1[0].cost);
}
else
sb.append(dp0[0].cnt+" "+dp0[0].cost);
sb.append("\n");
boolean[] include = new boolean[N];
Queue q = new Queue(500000);
q.add(current); q.add(tag);
while(q.size > 0)
{
int curr = q.poll();
tag = q.poll();
if(tag == 1)
include[curr] = true;
ArrayDeque<Integer> children = par0[curr];
if(tag == 1)
children = par1[curr];
for(int next: children)
{
q.add(abs(next));
int ntag = 0;
if(next < 0)
ntag = 1;
q.add(ntag);
}
}
for(int v=0; v < N; v++)
{
if(include[v])
sb.append(edges[v].length);
else
sb.append(1);
sb.append(' ');
}
System.out.println(sb);
}
static Node[] dp0;
static Node[] dp1;
static ArrayDeque<Integer>[] par0;
static ArrayDeque<Integer>[] par1;
public static void dfs(int curr, int par)
{
dp0[curr] = new Node();
dp1[curr] = new Node();
for(int next: edges[curr])
if(next != par)
{
dfs(next, curr);
dp1[curr].add(dp0[next]);
par1[curr].add(next);
if(dp0[next].compareTo(dp1[next]) < 0)
{
dp0[curr].add(dp0[next]);
par0[curr].add(next);
}
else
{
dp0[curr].add(dp1[next]);
par0[curr].add(-next);
}
}
dp0[curr].add(new Node(0, 1));
dp1[curr].add(new Node(1, edges[curr].length));
}
}
class Node
{
public int cnt;
public long cost;
public Node()
{
cnt = 0;
cost = 0;
}
public Node(int a, long b)
{
cnt = a;
cost = b;
}
public int compareTo(Node oth)
{
if(cnt == oth.cnt)
return Long.compare(cost, oth.cost);
return oth.cnt-cnt;
}
public void add(Node oth)
{
cnt += oth.cnt;
cost += oth.cost;
}
}
class FastScanner
{
//I don't understand how this works lmao
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
class Queue
{
private int[] arr;
private int MAX;
int head = 0;
int tail = 0;
int size = 0;
public Queue()
{
MAX = 1<<20;
arr = new int[MAX];
}
public Queue(int M)
{
MAX = M;
arr = new int[MAX];
}
public void add(int x)
{
arr[tail++] = x;
size++;
}
public int poll()
{
size--;
return arr[head++];
}
public void reset()
{
head = tail = size = 0;
}
public int size()
{
return size;
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | e1ec3841d51bb77c03b2d125cad3fe36 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | /*
Competitive Programming Template
*/
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1646D
{
static int[][] edges;
public static void main(String hi[]) throws Exception
{
FastScanner infile = new FastScanner();
int N = infile.nextInt();
if(N == 2)
{
System.out.println("2 2");
System.out.println("1 1");
return;
}
edges = new int[N][];
int[] input = new int[2*N-2];
int[] freq = new int[N];
for(int i=0; i < N-1; i++)
{
int a = infile.nextInt()-1;
int b = infile.nextInt()-1;
input[i<<1] = a;
input[(i<<1)+1] = b;
freq[a]++; freq[b]++;
}
for(int v=0; v < N; v++)
edges[v] = new int[freq[v]];
for(int i=1; i < 2*N-2; i+=2)
{
int a = input[i-1];
int b = input[i];
edges[a][--freq[a]] = b;
edges[b][--freq[b]] = a;
}
dp0 = new Node[N];
dp1 = new Node[N];
par0 = new ArrayDeque[N];
par1 = new ArrayDeque[N];
for(int i=0; i < N; i++)
{
par0[i] = new ArrayDeque<Integer>();
par1[i] = new ArrayDeque<Integer>();
}
dfs(0, -1);
int current = 0;
int tag = 0;
StringBuilder sb = new StringBuilder();
if(dp0[0].compareTo(dp1[0]) > 0)
{
tag = 1;
sb.append(dp1[0].cnt+" "+dp1[0].cost);
}
else
sb.append(dp0[0].cnt+" "+dp0[0].cost);
sb.append("\n");
boolean[] include = new boolean[N];
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
q.add(current); q.add(tag);
while(q.size() > 0)
{
int curr = q.poll();
tag = q.poll();
if(tag == 1)
include[curr] = true;
ArrayDeque<Integer> children = par0[curr];
if(tag == 1)
children = par1[curr];
for(int next: children)
{
q.add(abs(next));
int ntag = 0;
if(next < 0)
ntag = 1;
q.add(ntag);
}
}
for(int v=0; v < N; v++)
{
if(include[v])
sb.append(edges[v].length);
else
sb.append(1);
sb.append(' ');
}
System.out.println(sb);
}
static Node[] dp0;
static Node[] dp1;
static ArrayDeque<Integer>[] par0;
static ArrayDeque<Integer>[] par1;
public static void dfs(int curr, int par)
{
dp0[curr] = new Node();
dp1[curr] = new Node();
for(int next: edges[curr])
if(next != par)
{
dfs(next, curr);
dp1[curr].add(dp0[next]);
par1[curr].add(next);
if(dp0[next].compareTo(dp1[next]) < 0)
{
dp0[curr].add(dp0[next]);
par0[curr].add(next);
}
else
{
dp0[curr].add(dp1[next]);
par0[curr].add(-next);
}
}
dp0[curr].add(new Node(0, 1));
dp1[curr].add(new Node(1, edges[curr].length));
}
}
class Node
{
public int cnt;
public long cost;
public Node()
{
cnt = 0;
cost = 0;
}
public Node(int a, long b)
{
cnt = a;
cost = b;
}
public int compareTo(Node oth)
{
if(cnt == oth.cnt)
return Long.compare(cost, oth.cost);
return oth.cnt-cnt;
}
public void add(Node oth)
{
cnt += oth.cnt;
cost += oth.cost;
}
}
class FastScanner
{
//I don't understand how this works lmao
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 49c0ae57357c7d64c5c5f85796e03e7d | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | /*
Competitive Programming Template
*/
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1646D
{
static ArrayDeque<Integer>[] edges;
public static void main(String hi[]) throws Exception
{
FastScanner infile = new FastScanner();
int N = infile.nextInt();
if(N == 2)
{
System.out.println("2 2");
System.out.println("1 1");
return;
}
edges = new ArrayDeque[N];
for(int v=0; v < N; v++)
edges[v] = new ArrayDeque<Integer>();
for(int i=1; i < N; i++)
{
int a = infile.nextInt()-1;
int b = infile.nextInt()-1;
edges[a].add(b); edges[b].add(a);
}
dp0 = new Node[N];
dp1 = new Node[N];
par0 = new ArrayDeque[N];
par1 = new ArrayDeque[N];
for(int i=0; i < N; i++)
{
par0[i] = new ArrayDeque<Integer>();
par1[i] = new ArrayDeque<Integer>();
}
dfs(0, -1);
int current = 0;
int tag = 0;
StringBuilder sb = new StringBuilder();
if(dp0[0].compareTo(dp1[0]) > 0)
{
tag = 1;
sb.append(dp1[0].cnt+" "+dp1[0].cost);
}
else
sb.append(dp0[0].cnt+" "+dp0[0].cost);
sb.append("\n");
boolean[] include = new boolean[N];
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
q.add(current); q.add(tag);
while(q.size() > 0)
{
int curr = q.poll();
tag = q.poll();
if(tag == 1)
include[curr] = true;
ArrayDeque<Integer> children = par0[curr];
if(tag == 1)
children = par1[curr];
for(int next: children)
{
q.add(abs(next));
int ntag = 0;
if(next < 0)
ntag = 1;
q.add(ntag);
}
}
for(int v=0; v < N; v++)
{
if(include[v])
sb.append(edges[v].size()+" ");
else
sb.append("1 ");
}
System.out.println(sb);
}
static Node[] dp0;
static Node[] dp1;
static ArrayDeque<Integer>[] par0;
static ArrayDeque<Integer>[] par1;
public static void dfs(int curr, int par)
{
dp0[curr] = new Node();
dp1[curr] = new Node();
for(int next: edges[curr])
if(next != par)
{
dfs(next, curr);
dp1[curr].add(dp0[next]);
par1[curr].add(next);
if(dp0[next].compareTo(dp1[next]) < 0)
{
dp0[curr].add(dp0[next]);
par0[curr].add(next);
}
else
{
dp0[curr].add(dp1[next]);
par0[curr].add(-next);
}
}
dp0[curr].add(new Node(0, 1));
dp1[curr].add(new Node(1, edges[curr].size()));
}
}
class Node
{
public int cnt;
public long cost;
public Node()
{
cnt = 0;
cost = 0;
}
public Node(int a, long b)
{
cnt = a;
cost = b;
}
public int compareTo(Node oth)
{
if(cnt == oth.cnt)
return Long.compare(cost, oth.cost);
return oth.cnt-cnt;
}
public void add(Node oth)
{
cnt += oth.cnt;
cost += oth.cost;
}
}
class FastScanner
{
//I don't understand how this works lmao
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 27c97a0e74c2cbcafe96c198a490a307 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | /*
Competitive Programming Template
*/
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1646D
{
static ArrayDeque<Integer>[] edges;
public static void main(String hi[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
if(N == 2)
{
System.out.println("2 2");
System.out.println("1 1");
return;
}
edges = new ArrayDeque[N];
for(int v=0; v < N; v++)
edges[v] = new ArrayDeque<Integer>();
for(int i=1; i < N; i++)
{
st = new StringTokenizer(infile.readLine());
int a = Integer.parseInt(st.nextToken())-1;
int b = Integer.parseInt(st.nextToken())-1;
edges[a].add(b); edges[b].add(a);
}
dp0 = new Node[N];
dp1 = new Node[N];
par0 = new ArrayDeque[N];
par1 = new ArrayDeque[N];
for(int i=0; i < N; i++)
{
par0[i] = new ArrayDeque<Integer>();
par1[i] = new ArrayDeque<Integer>();
}
dfs(0, -1);
int current = 0;
int tag = 0;
StringBuilder sb = new StringBuilder();
if(dp0[0].compareTo(dp1[0]) > 0)
{
tag = 1;
sb.append(dp1[0].cnt+" "+dp1[0].cost);
}
else
sb.append(dp0[0].cnt+" "+dp0[0].cost);
sb.append("\n");
boolean[] include = new boolean[N];
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
q.add(current); q.add(tag);
while(q.size() > 0)
{
int curr = q.poll();
tag = q.poll();
if(tag == 1)
include[curr] = true;
ArrayDeque<Integer> children = par0[curr];
if(tag == 1)
children = par1[curr];
for(int next: children)
{
q.add(abs(next));
int ntag = 0;
if(next < 0)
ntag = 1;
q.add(ntag);
}
}
for(int v=0; v < N; v++)
{
if(include[v])
sb.append(edges[v].size()+" ");
else
sb.append("1 ");
}
System.out.println(sb);
}
static Node[] dp0;
static Node[] dp1;
static ArrayDeque<Integer>[] par0;
static ArrayDeque<Integer>[] par1;
public static void dfs(int curr, int par)
{
dp0[curr] = new Node();
dp1[curr] = new Node();
for(int next: edges[curr])
if(next != par)
{
dfs(next, curr);
dp1[curr].add(dp0[next]);
par1[curr].add(next);
if(dp0[next].compareTo(dp1[next]) < 0)
{
dp0[curr].add(dp0[next]);
par0[curr].add(next);
}
else
{
dp0[curr].add(dp1[next]);
par0[curr].add(-next);
}
}
dp0[curr].add(new Node(0, 1));
dp1[curr].add(new Node(1, edges[curr].size()));
}
}
class Node
{
public int cnt;
public long cost;
public Node()
{
cnt = 0;
cost = 0;
}
public Node(int a, long b)
{
cnt = a;
cost = b;
}
public int compareTo(Node oth)
{
if(cnt == oth.cnt)
return Long.compare(cost, oth.cost);
return oth.cnt-cnt;
}
public void add(Node oth)
{
cnt += oth.cnt;
cost += oth.cost;
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 52616fe92e83d0c614e18760b938ef2f | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | // package faltu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import java.util.Map.Entry;
public class Main {
// ***********************MATHS--STARTS************************************************* //
private static ArrayList<Long> get_divisor(long x) {
ArrayList<Long>a=new ArrayList<Long>();
for(long i=1;i*i<=x;i++) {
if(x%i==0) {
a.add((long) i);
if(x/i!=i)a.add(x/i);
}
}
return a;
}
static long[] sieve;
static long[] smallestPrime;
public static void sieve()
{
int n=4000000+1;
sieve=new long[n];
smallestPrime=new long[n];
sieve[0]=1;
sieve[1]=1;
for(int i=2;i<n;i++){
sieve[i]=i;
smallestPrime[i]=i;
}
for(int i=2;i*i<n;i++){
if(sieve[i]==i){
for(int j=i*i;j<n;j+=i){
if(sieve[j]==j)sieve[j]=1;
if(smallestPrime[j]==j||smallestPrime[j]>i)smallestPrime[j]=i;
}
}
}
}
static long nCr(long n,long r,long MOD) {
if(n<r)return 0;
if(r==0)return 1;
return fact[(int) n]*mod_inv(fact[(int) r],MOD)%MOD*mod_inv(fact[(int) (n-r)],MOD)%MOD;
}
static long[]fact;
static void computeFact(long n,long MOD) {
fact=new long[(int)n+1];
fact[0]=1;
for(int i=1;i<=n;i++)fact[i]=(fact[i-1]*i%MOD)%MOD;
}
static long bin_expo(long a,long b,long MOD) {
if(b == 0)return 1;
long ans = bin_expo(a,b/2,MOD);
ans = (ans*ans)%MOD;
if(b % 2!=0){
ans = (ans*a)%MOD;
}
return ans%MOD;
}
static long mod_add(long a, long b, long m) {a = a % m; b = b % m; return (((a + b) % m) + m) % m;}
static long mod_mul(long a, long b, long m) {a = a % m; b = b % m; return (((a * b) % m) + m) % m;}
static long mod_sub(long a, long b, long m) {a = a % m; b = b % m; return (((a - b) % m) + m) % m;}
static long mod_inv(long n,long p) {return bin_expo(n,p-2,p);}
static long gcd(long a, long b){if (a == 0) {return b;}return gcd(b % a, a); }
static int gcd(int a, int b){if (a == 0) {return b; }return gcd(b % a, a); }
static long lcm(long a,long b){return (a / gcd(a, b)) * b;}
static ArrayList<String>powof2s;
static void powof2S() {
long i=1;
while(i<(long)2e18) {
powof2s.add(String.valueOf(i));
i*=2;
}
}
static long power(long a, long b){
a %=MOD;long out = 1;
while (b > 0) {
if((b&1)!=0)out = out * a % MOD;
a = a * a % MOD;
b >>= 1;
a*=a;
}
return out;
}
static boolean coprime(int a, long l){return (gcd(a, l) == 1);}
// ****************************MATHS-ENDS*****************************************************
// ***********************BINARY-SEARCH STARTS***********************************************
public static int upperBound(long[] arr, long m, int l, int r) {
while(l<=r) {
int mid=(l+r)/2;
if(arr[mid]<=m) l=mid+1;
else r=mid-1;
}
return l;
}
public static int lowerBound(long[] a, long m, int l, int r) {
while(l<=r) {
int mid=(l+r)/2;
if(a[mid]<m) l=mid+1;
else r=mid-1;
}
return l;
}
public static int lowerBound(ArrayList<Integer> ar,int k){
int s=0,e=ar.size();
while (s!=e){
int mid = s+e>>1;
if (ar.get(mid) <k)s=mid+1;
else e=mid;
}
if(s==ar.size())return -1;
return s;
}
public static int upperBound(ArrayList<Integer> ar,int k){
int s=0,e=ar.size();
while (s!=e){
int mid = s+e>>1;
if (ar.get(mid) <=k)s=mid+1;
else e=mid;
}
if(s==ar.size())return -1;
return s;
}
public static long getClosest(long val1, long val2,long target)
{
if (target - val1 >= val2 - target)
return val2;
else
return val1;
}
static void ruffleSort(long[] a) {
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
long oi=r.nextInt(n), temp=a[i];
a[i]=a[(int)oi];
a[(int)oi]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(int[] a){
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n), temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
Arrays.sort(a);
}
int ceilIndex(int input[], int T[], int end, int s){
int start = 0;
int middle;
int len = end;
while(start <= end){
middle = (start + end)/2;
if(middle < len && input[T[middle]] < s && s <= input[T[middle+1]]){
return middle+1;
}else if(input[T[middle]] < s){
start = middle+1;
}else{
end = middle-1;
}
}
return -1;
}
static int lowerLimitBinarySearch(ArrayList<Long> v,long k) {
int n =v.size();
int first = 0,second = n;
while(first <second) {
int mid = first + (second-first)/2;
if(v.get(mid) > k) {
second = mid;
}else {
first = mid+1;
}
}
if(first < n && v.get(first) < k) {
first++;
}
return first; //1 index
}
public static int searchindex(long arr[], long t){
int index = Arrays.binarySearch(arr, t);
return (index < 0) ? -1 : index;
}
public static int[] sort(int[] arr) {
ArrayList<Integer> al = new ArrayList<>();
for(int i=0;i<arr.length;i++) al.add(arr[i]);
Collections.sort(al);
for(int i=0;i<arr.length;i++) arr[i]=al.get(i);
return arr;
}
// *******************************BINARY-SEARCH ENDS***********************************************
// *********************************GRAPHS-STARTS****************************************************
// *******----SEGMENT TREE IMPLEMENT---*****
// -------------START---------------
void buildTree (int[] arr,int[] tree,int start,int end,int treeNode)
{
if(start==end)
{
tree[treeNode]=arr[start];
return;
}
buildTree(arr,tree,start,end,2*treeNode);
buildTree(arr,tree,start,end,2*treeNode+1);
tree[treeNode]=tree[treeNode*2]+tree[2*treeNode+1];
}
void updateTree(int[] arr,int[] tree,int start,int end,int treeNode,int idx,int value)
{
if(start==end)
{
arr[idx]=value;
tree[treeNode]=value;
return;
}
int mid=(start+end)/2;
if(idx>mid)
{
updateTree(arr,tree,mid+1,end,2*treeNode+1,idx,value);
}
else
{
updateTree(arr,tree,start,mid,2*treeNode,idx,value);
}
tree[treeNode]=tree[2*treeNode]+tree[2*treeNode+1];
}
// -------------ENDS---------------
//***********************DSU IMPLEMENT START*************************
static int parent[];
static int rank[];
static void makeSet(int n)
{
parent=new int[n];
rank=new int[n];
for(int i=0;i<n;i++)
{
parent[i]=i;
rank[i]=0;
}
}
static void union(int u,int v)
{
u=findpar(u);
v=findpar(v);
if(rank[u]<rank[v])parent[u]=v;
else if(rank[v]<rank[u])parent[v]=u;
else
{
parent[v]=u;
rank[u]++;
}
}
private static int findpar(int node)
{
if(node==parent[node])return node;
return parent[node]=findpar(parent[node]);
}
// *********************DSU IMPLEMENT ENDS*************************
public static void setGraph(int n,int m){
adj=new ArrayList[n+1];
for(int i=0;i<=n;i++){
adj[i]=new ArrayList<>();
}
for(int i=0;i<m;i++){
int u=s.nextInt(),v=s.nextInt();
adj[u].add(v);
adj[v].add(u);
}
}
// *********************************GRAPHS-ENDS****************************************************
static int[][] dirs8 = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};
static int[][] dirs4 = {{1,0},{-1,0},{0,1},{0,-1}};
static long MOD=(long) (1e9+7);
static int prebitsum[][];
static ArrayList<Integer>arr;
static boolean[] vis;
// static ArrayList<ArrayList<Integer>>adj;
static ArrayList<Integer> adj[];
static FastReader s = new FastReader(System.in);
static PrintWriter out = new PrintWriter(System.out, false);
public static void main(String[] args) throws IOException
{
// sieve();
// computeFact((int)1e7+1,MOD);
// prebitsum=new int[2147483648][31];
// presumbit(prebitsum);
// powof2S();
// int tt = s.nextInt();
int tt=1;
while(tt-->0) {
solve();
}
}
static pair[]dpGood,dpBad;
static long[]ans;
static boolean[]taken;
private static void solve() {
int n=s.nextInt();
if(n==2) {
System.out.println(2+" "+2);
System.out.println(1+" "+1);
return;
}
dpGood=new pair[n+1];
dpBad=new pair[n+1];
ans=new long[n+1];
taken=new boolean[n+1];
setGraph(n, n-1);
dfs(1,0);
if(dpGood[1].greater(dpBad[1])) {
ans[1]=adj[1].size();
System.out.println(dpGood[1].x+" "+(-dpGood[1].y));
taken[1]=true;
}
else {
ans[1]=1;
System.out.println(dpBad[1].x+" "+(-dpBad[1].y));
}
for(Integer it:adj[1]) {
dfs2(it,1);
}
for(int i=1;i<=n;i++)System.out.print(ans[i]+" ");
return;
}
private static void dfs2(int u,int p) {
if(taken[p]||(!dpGood[u].greater(dpBad[u]))){
ans[u]=1;
}
else {
taken[u]=true;
ans[u]=adj[u].size();
}
for(Integer it:adj[u]) {
if(it!=p)dfs2(it,u);
}
}
private static void dfs(int u, int p) {
dpGood[u]=new pair(1,-adj[u].size());
dpBad[u]=new pair(0,-1);
for(Integer it:adj[u]) {
if(it!=p) {
dfs(it,u);
dpGood[u].x+=dpBad[it].x;
dpGood[u].y+=dpBad[it].y;
if(dpGood[it].greater(dpBad[it])) {
dpBad[u].x+=dpGood[it].x;
dpBad[u].y+=dpGood[it].y;
}
else {
dpBad[u].x+=dpBad[it].x;
dpBad[u].y+=dpBad[it].y;
}
}
}
}
// *********************BITS && TOOLS &&DEBUG STARTS***********************************************
static void presumbit(int[][]prebitsum) {
for(int i=1;i<=200000;i++) {
int z=i;
int j=0;
while(z>0) {
if((z&1)==1) {
prebitsum[i][j]+=(prebitsum[i-1][j]+1);
}else {
prebitsum[i][j]=prebitsum[i-1][j];
}
z=z>>1;
j++;
}
}
}
static void countOfSetBit(long[]a) {
for(int j=30;j>=0;j--) {
int cnt=0;
for(long i:a) {
if((i&1<<j)==1)cnt++;
}
// printing the current no set bit in all array element
System.out.println(cnt);
}
}
public static String revStr(String str){
String input = str;
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1.reverse();
return input1.toString();
}
static boolean issafe(int i, int j, int r,int c, char ch){
if (i < 0 || j < 0 || i >= r || j >= c|| ch!= '1')return false;
else return true;
}
static void pc2d(char[][]a) {
int n=a.length;
int m=a[0].length;
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
static void pi2d(int[][] dp12) {
int n=dp12.length;
int m=dp12[0].length;
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
System.out.print(dp12[i][j]+" ");
}
System.out.println();
}
}
// *****************BITS && TOOLS &&DEBUG ENDS***********************************************
// **************************I/O*************************
static class FastReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
class decrease implements Comparator<Long> {
// Used for sorting in ascending order of
// roll number
public int compare(long a, long b)
{
return (int) (b - a);
}
@Override
public int compare(Long o1, Long o2) {
// TODO Auto-generated method stub
return (int) (o2-o1);
}
}
class pair{
long x;
long y;
public pair(long x,long y) {
this.x=x;
this.y=y;
}
public boolean greater(pair node) {
if (x > node.x || (x == node.x && y > node.y)) {
return true;
}
return false;
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 72d563182200b782a0d41c099c017880 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.Math;
public class Main {
public class MainSolution extends MainSolutionT {
// global vars
public void init(int tests_count){}
public class TestCase extends TestCaseT
{
int N;
int[] adj_count;
int[][] adj_list;
int[] good, bad;
int[] gt;
long[] wgood;
long[] wbad;
int[] W;
boolean[] is_good;
public void dfs(int u, int p)
{
int v;
int _gs = 0;
int _bs = 0;
long wg = 0, wb = 0;
for (int i=0; i<adj_count[u]; i++)
{
v = adj_list[u][i];
if (v != p)
{
dfs(v, u);
_bs += bad[v];
_gs += good[v];
wb += wbad[v];
wg += wgood[v];
}
}
bad[u] = _gs;
wbad[u] = wg + 1;
if ((1+_bs > _gs) || ((1+_bs == _gs) && ( wb+adj_count[u] < wg+1 )))
{
wgood[u] = wb + adj_count[u];
good[u] = 1+_bs;
gt[u] = 1;
}
else
{
wgood[u] = wg + 1;
gt[u] = 0;
good[u] = _gs;
}
}
public void fill(int u, int p, int g)
{
is_good[u] = (g==1) && (gt[u]==1);
if (!is_good[u])
{
W[u] = 1;
}
else
{
W[u] = adj_count[u];
}
int v;
for (int i=0; i<adj_count[u]; i++)
{
v = adj_list[u][i];
if (v != p)
{
fill(v, u, is_good[u] ? 0 : 1);
}
}
}
public Object solve()
{
N = readInt();
int[] v = new int[N-1];
int[] u = new int[N-1];
adj_count = new int[N];
adj_list = new int[N][];
Arrays.fill(adj_count, 0);
int i;
for (i=0; i<N-1; i++)
{
u[i] = readInt()-1;
v[i] = readInt()-1;
adj_count[u[i]] ++;
adj_count[v[i]] ++;
}
for (i=0; i<N; i++)
{
adj_list[i] = new int[adj_count[i]];
adj_count[i] = 0;
}
for (i=0; i<N-1; i++)
{
adj_list[u[i]][ adj_count[u[i]]++ ] = v[i];
adj_list[v[i]][ adj_count[v[i]]++ ] = u[i];
}
good = new int[N];
bad = new int[N];
gt = new int[N];
W = new int[N];
is_good = new boolean[N];
wgood = new long[N];
wbad = new long[N];
if (N == 2)
{
out.println("2 2");
out.println("1 1");
return null;
}
dfs(0, -1);
fill(0, -1, 1);
long ws = 0;
int gc = 0;
for (i=0; i<N; i++)
{
ws += W[i];
if (is_good[i])
{
gc ++;
}
}
out.printf("%d %d\n", gc, ws);
printArray(W, N);
return null;
}
}
public void run()
{
int t = multiply_test ? readInt() : 1;
this.init(t);
for (int i = 0; i < t; i++) {
TestCase T = new TestCase();
T.run(i + 1);
}
}
public void loc_params()
{
this.log_enabled = false;
}
public void params(){
this.multiply_test = false;
}
}
public class MainSolutionT extends MainSolutionBase
{
public class TestCaseT extends TestCaseBase
{
}
}
public class MainSolutionBase
{
public boolean is_local = false;
public MainSolutionBase()
{
}
public class TestCaseBase
{
public Object solve() {
return null;
}
public int caseNumber;
public TestCaseBase() {
}
public void run(int cn){
this.caseNumber = cn;
Object r = this.solve();
if ((r != null))
{
out.println(r);
}
}
}
public String impossible(){
return "IMPOSSIBLE";
}
public String strf(String format, Object... args)
{
return String.format(format, args);
}
public BufferedReader in;
public PrintStream out;
public boolean log_enabled = false;
public boolean multiply_test = true;
public void params()
{
}
public void loc_params()
{
}
private StringTokenizer tokenizer = null;
public int readInt() {
return Integer.parseInt(readToken());
}
public long readLong() {
return Long.parseLong(readToken());
}
public double readDouble() {
return Double.parseDouble(readToken());
}
public String readLn() {
try {
String s;
while ((s = in.readLine()).length() == 0);
return s;
} catch (Exception e) {
return "";
}
}
public String readToken() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
} catch (Exception e) {
return "";
}
}
public int[] readIntArray(int n) {
int[] x = new int[n];
readIntArray(x, n);
return x;
}
public void readIntArray(int[] x, int n) {
for (int i = 0; i < n; i++) {
x[i] = readInt();
}
}
public long[] readLongArray(int n) {
long[] x = new long[n];
readLongArray(x, n);
return x;
}
public void readLongArray(long[] x, int n) {
for (int i = 0; i < n; i++) {
x[i] = readLong();
}
}
public void readLongArrayRev(long[] x, int n) {
for (int i = 0; i < n; i++) {
x[n-i-1] = readLong();
}
}
public void logWrite(String format, Object... args) {
if (!log_enabled) {
return;
}
out.printf(format, args);
}
public void readLongArrayBuf(long[] x, int n) {
char[]buf = new char[1000000];
long r = -1;
int k= 0, l = 0;
long d;
while (true)
{
try{
l = in.read(buf, 0, 1000000);
}
catch(Exception E){};
for (int i=0; i<l; i++)
{
if (('0'<=buf[i])&&(buf[i]<='9'))
{
if (r == -1)
{
r = 0;
}
d = buf[i] - '0';
r = 10 * r + d;
}
else
{
if (r != -1)
{
x[k++] = r;
}
r = -1;
}
}
if (l<1000000)
return;
}
}
public void readIntArrayBuf(int[] x, int n) {
char[]buf = new char[1000000];
int r = -1;
int k= 0, l = 0;
int d;
while (true)
{
try{
l = in.read(buf, 0, 1000000);
}
catch(Exception E){};
for (int i=0; i<l; i++)
{
if (('0'<=buf[i])&&(buf[i]<='9'))
{
if (r == -1)
{
r = 0;
}
d = buf[i] - '0';
r = 10 * r + d;
}
else
{
if (r != -1)
{
x[k++] = r;
}
r = -1;
}
}
if (l<1000000)
return;
}
}
public void printArray(long[] a, int n)
{
printArray(a, n, ' ');
}
public void printArray(int[] a, int n)
{
printArray(a, n, ' ');
}
public void printArray(long[] a, int n, char dl)
{
long x;
int i, l = 0;
for (i=0; i<n; i++)
{
x = a[i];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
x = a[i];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (i>0)
{
s[l--] = dl;
}
}
out.println(new String(s));
}
public void printArray(double[] a, int n, char dl)
{
long x;
double y;
int i, l = 0;
for (i=0; i<n; i++)
{
x = (long)a[i];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += n-1 + 10*n;
char[] s = new char[l];
l--;
boolean z;
int j;
for (i=n-1; i>=0; i--)
{
x = (long)a[i];
y = (long)(1000000000*(a[i]-x));
z = false;
if (x<0)
{
x = -x;
z = true;
}
for (j=0; j<9; j++)
{
s[l--] = (char)('0' + (y % 10));
y /= 10;
}
s[l--] = '.';
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (i>0)
{
s[l--] = dl;
}
}
out.println(new String(s));
}
public void printArray(int[] a, int n, char dl)
{
int x;
int i, l = 0;
for (i=0; i<n; i++)
{
x = a[i];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
x = a[i];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (i>0)
{
s[l--] = dl;
}
}
out.println(new String(s));
}
public void printMatrix(int[][] a, int n, int m)
{
int x;
int i,j, l = 0;
for (i=0; i<n; i++)
{
for (j=0; j<m; j++)
{
x = a[i][j];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += m-1;
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
for (j=m-1; j>=0; j--)
{
x = a[i][j];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (j>0)
{
s[l--] = ' ';
}
}
if (i>0)
{
s[l--] = '\n';
}
}
out.println(new String(s));
}
public void printMatrix(long[][] a, int n, int m)
{
long x;
int i,j, l = 0;
for (i=0; i<n; i++)
{
for (j=0; j<m; j++)
{
x = a[i][j];
if (x<0)
{
x = -x;
l++;
}
if (x==0)
{
l++;
}
else
{
while (x>0)
{
x /= 10;
l++;
}
}
}
l += m-1;
}
l += n-1;
char[] s = new char[l];
l--;
boolean z;
for (i=n-1; i>=0; i--)
{
for (j=m-1; j>=0; j--)
{
x = a[i][j];
z = false;
if (x<0)
{
x = -x;
z = true;
}
do{
s[l--] = (char)('0' + (x % 10));
x /= 10;
} while (x>0);
if (z)
{
s[l--] = '-';
}
if (j>0)
{
s[l--] = ' ';
}
}
if (i>0)
{
s[l--] = '\n';
}
}
out.println(new String(s));
}
}
public void run()
{
MainSolution S;
try {
S = new MainSolution();
S.in = new BufferedReader(new InputStreamReader(System.in));
//S.out = System.out;
S.out = new PrintStream(new BufferedOutputStream( System.out ));
} catch (Exception e) {
return;
}
S.params();
S.run();
S.out.flush();
}
public static void main(String args[]) {
Locale.setDefault(Locale.US);
Main M = new Main();
M.run();
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | a12fefcf77b4344908343e7973ea5ef6 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
// int a = 1;
int t;
//t = in.nextInt();
t = 1;
while (t > 0) {
// out.print("Case #"+(a++)+": ");
solver.call(in,out);
t--;
}
out.close();
}
static class TaskA {
Map<Integer, List<Integer>> map = new HashMap<>();
answer[][] dp;
int[] arr;
public void call(InputReader in, PrintWriter out) {
int n, u, v;
n = in.nextInt();
dp = new answer[n + 10][3];
arr = new int[n + 1];
for(int i = 0; i < n - 1; i++){
u = in.nextInt() - 1;
v = in.nextInt() - 1;
map.putIfAbsent(u, new ArrayList<>());
map.get(u).add(v);
map.putIfAbsent(v, new ArrayList<>());
map.get(v).add(u);
}
if(n == 2){
out.println(2+" "+2);
out.println(1+" "+1);
return;
}
Arrays.fill(arr, 1);
answer temp = ans(0,-1,0);
int ans = temp.a;
long sum = temp.b;
ans1(0,-1,0);
out.println(ans +" "+sum);
for (int i = 0; i < n; i++) {
out.print(arr[i]+" ");
}
out.println();
}
public answer ans(int index, int par, int prev){
if(dp[index][prev] != null){
return dp[index][prev];
}
answer opt = new answer(0,0), opt1 = new answer(0,0), opt2;
if(prev == 0){
opt.a = 1;
opt.b = map.get(index).size();
opt1.b++;
for(Integer i : map.get(index)){
if(i != par){
opt2 = ans(i, index, 1);
opt.a += opt2.a;
opt.b += opt2.b;
opt2 = ans(i, index, 0);
opt1.a += opt2.a;
opt1.b += opt2.b;
}
}
if(opt.a > opt1.a){
return dp[index][prev] = new answer(opt.a, opt.b);
}
else if(opt.a == opt1.a){
if(opt.b > opt1.b){
return dp[index][prev] = new answer(opt1.a, opt1.b);
}
else{
return dp[index][prev] = new answer(opt.a, opt.b);
}
}
else{
return dp[index][prev] = new answer(opt1.a, opt1.b);
}
}
else{
opt.b = 1;
for(Integer i : map.get(index)){
if(i != par){
opt2 = ans(i, index, 0);
opt.a += opt2.a;
opt.b += opt2.b;
}
}
return dp[index][prev] = new answer(opt.a, opt.b);
}
}
public void ans1(int index, int par, int prev){
answer opt = new answer(0,0), opt1 = new answer(0,0), opt2;
if(prev == 0){
opt.a = 1;
opt.b = map.get(index).size();
opt1.b++;
for(Integer i : map.get(index)){
if(i != par){
opt2 = ans(i, index, 1);
opt.a += opt2.a;
opt.b += opt2.b;
opt2 = ans(i, index, 0);
opt1.a += opt2.a;
opt1.b += opt2.b;
}
}
if(opt.a > opt1.a){
arr[index] = map.get(index).size();
for(Integer i : map.get(index)){
if(i != par){
ans1(i, index, 1);
}
}
}
else if(opt.a == opt1.a){
if(opt.b > opt1.b){
for(Integer i : map.get(index)){
if(i != par){
ans1(i, index, 0);
}
}
}
else{
arr[index] = map.get(index).size();
for(Integer i : map.get(index)){
if(i != par){
ans1(i, index, 1);
}
}
}
}
else{
for(Integer i : map.get(index)){
if(i != par){
ans1(i, index, 0);
}
}
}
}
else{
for(Integer i : map.get(index)){
if(i != par){
ans1(i, index, 0);
}
}
}
}
}
static long mod = 1_000_000_007;
static long mul(long a, long b) {
return a * b % mod;
}
static long exp(long base, long pow) {
if (pow == 0) return 1;
long half = exp(base, pow / 2);
if (pow % 2 == 0) return mul(half, half);
return mul(half, mul(half, base));
}
static int gcd(int a, int b )
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static class answer implements Comparable<answer>{
int c, a;
long b;
public answer(int a, long b){
this.a = a;
this.b = b;
}
public answer(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int compareTo(answer o) {
return Integer.compare(this.a, o.a);
}
}
static class answer1 implements Comparable<answer1>{
int a, b, c;
public answer1(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public answer1(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(answer1 o) {
if(this.b == o.b){
return Integer.compare(this.a, o.a);
}
return Integer.compare(this.b, o.b);
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (Long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static final Random random=new Random();
static void shuffleSort(int[] a) {
int n = a.length;
for (int i=0; i<n; i++) {
int oi= random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | e449084ecb4727b7aa1234cf0acb6fb3 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
// int a = 1;
int t;
//t = in.nextInt();
t = 1;
while (t > 0) {
// out.print("Case #"+(a++)+": ");
solver.call(in,out);
t--;
}
out.close();
}
static class TaskA {
Map<Integer, List<Integer>> map = new HashMap<>();
answer[][] dp;
int[] arr;
public void call(InputReader in, PrintWriter out) {
int n, u, v;
n = in.nextInt();
dp = new answer[n + 10][3];
arr = new int[n + 1];
for(int i = 0; i < n - 1; i++){
u = in.nextInt() - 1;
v = in.nextInt() - 1;
map.putIfAbsent(u, new ArrayList<>());
map.get(u).add(v);
map.putIfAbsent(v, new ArrayList<>());
map.get(v).add(u);
}
if(n == 2){
out.println(2+" "+2);
out.println(1+" "+1);
return;
}
Arrays.fill(arr, 1);
answer temp = ans(0,-1,0);
int ans = temp.a;
long sum = temp.b;
ans1(0,-1,0);
for (int i = 0; i < n; i++) {
if(arr[i] == 2){
u = 0;
for(Integer j : map.get(i)){
u += arr[j];
}
arr[i] = u;
}
}
out.println(ans +" "+sum);
for (int i = 0; i < n; i++) {
out.print(arr[i]+" ");
}
out.println();
}
public answer ans(int index, int par, int prev){
if(dp[index][prev] != null){
return dp[index][prev];
}
answer opt = new answer(0,0), opt1 = new answer(0,0), opt2;
if(prev == 0){
opt.a = 1;
opt.b = map.get(index).size();
opt1.b++;
for(Integer i : map.get(index)){
if(i != par){
opt2 = ans(i, index, 1);
opt.a += opt2.a;
opt.b += opt2.b;
opt2 = ans(i, index, 0);
opt1.a += opt2.a;
opt1.b += opt2.b;
}
}
if(opt.a > opt1.a){
return dp[index][prev] = new answer(opt.a, opt.b);
}
else if(opt.a == opt1.a){
if(opt.b > opt1.b){
return dp[index][prev] = new answer(opt1.a, opt1.b);
}
else{
return dp[index][prev] = new answer(opt.a, opt.b);
}
}
else{
return dp[index][prev] = new answer(opt1.a, opt1.b);
}
}
else{
opt.b = 1;
for(Integer i : map.get(index)){
if(i != par){
opt2 = ans(i, index, 0);
opt.a += opt2.a;
opt.b += opt2.b;
}
}
return dp[index][prev] = new answer(opt.a, opt.b);
}
}
public void ans1(int index, int par, int prev){
answer opt = new answer(0,0), opt1 = new answer(0,0), opt2;
if(prev == 0){
opt.a = 1;
opt.b = map.get(index).size();
opt1.b++;
for(Integer i : map.get(index)){
if(i != par){
opt2 = ans(i, index, 1);
opt.a += opt2.a;
opt.b += opt2.b;
opt2 = ans(i, index, 0);
opt1.a += opt2.a;
opt1.b += opt2.b;
}
}
if(opt.a > opt1.a){
arr[index] = 2;
for(Integer i : map.get(index)){
if(i != par){
ans1(i, index, 1);
}
}
}
else if(opt.a == opt1.a){
if(opt.b > opt1.b){
for(Integer i : map.get(index)){
if(i != par){
ans1(i, index, 0);
}
}
}
else{
arr[index] = 2;
for(Integer i : map.get(index)){
if(i != par){
ans1(i, index, 1);
}
}
}
}
else{
for(Integer i : map.get(index)){
if(i != par){
ans1(i, index, 0);
}
}
}
}
else{
for(Integer i : map.get(index)){
if(i != par){
ans1(i, index, 0);
}
}
}
}
}
static long mod = 1_000_000_007;
static long mul(long a, long b) {
return a * b % mod;
}
static long exp(long base, long pow) {
if (pow == 0) return 1;
long half = exp(base, pow / 2);
if (pow % 2 == 0) return mul(half, half);
return mul(half, mul(half, base));
}
static int gcd(int a, int b )
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static class answer implements Comparable<answer>{
int c, a;
long b;
public answer(int a, long b){
this.a = a;
this.b = b;
}
public answer(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public int compareTo(answer o) {
return Integer.compare(this.a, o.a);
}
}
static class answer1 implements Comparable<answer1>{
int a, b, c;
public answer1(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public answer1(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(answer1 o) {
if(this.b == o.b){
return Integer.compare(this.a, o.a);
}
return Integer.compare(this.b, o.b);
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (Long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static final Random random=new Random();
static void shuffleSort(int[] a) {
int n = a.length;
for (int i=0; i<n; i++) {
int oi= random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | accb97406a464c5f04f92afda7c10caa | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
//--------------------------INPUT READER---------------------------------//
static class fs {
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public fs() { this(System.in); }
public fs(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
int ni() { return Integer.parseInt(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String ns() { return next(); }
int[] na(long nn) {
int n = (int) nn;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
long[] nal(long nn) {
int n = (int) nn;
long[] l = new long[n];
for(int i = 0; i < n; i++) l[i] = nl();
return l;
}
}
//-----------------------------------------------------------------------//
//---------------------------PRINTER-------------------------------------//
static class Printer {
static PrintWriter w;
public Printer() {this(System.out);}
public Printer(OutputStream os) {
w = new PrintWriter(os);
}
public void p(int i) {w.println(i);}
public void p(long l) {w.println(l);}
public void p(double d) {w.println(d);}
public void p(String s) { w.println(s);}
public void pr(int i) {w.print(i);}
public void pr(long l) {w.print(l);}
public void pr(double d) {w.print(d);}
public void pr(String s) { w.print(s);}
public void pl() {w.println();}
public void close() {w.close();}
}
//-----------------------------------------------------------------------//
//--------------------------VARIABLES------------------------------------//
static fs sc = new fs();
static OutputStream outputStream = System.out;
static Printer w = new Printer(outputStream);
static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
static long mod = 1000000007;
//-----------------------------------------------------------------------//
//--------------------------ADMIN_MODE-----------------------------------//
private static void ADMIN_MODE() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
w = new Printer(new FileOutputStream("output.txt"));
sc = new fs(new FileInputStream("input.txt"));
}
}
//-----------------------------------------------------------------------//
//----------------------------START--------------------------------------//
public static void main(String[] args)
throws IOException {
ADMIN_MODE();
//int t = sc.ni();while(t-->0)
solve();
w.close();
}
static List<List<Integer>> graph;
static pr[][] dp;
static int[] weights;
static pr compare(pr a, pr b) {
if(a == null) return b;
if(b == null) return a;
if(a.freq != b.freq) {
return (a.freq > b.freq) ? a : b;
} else {
return (a.wt < b.wt) ? a : b;
}
}
static pr dfs(int at, int pt, boolean allowed) {
int id = (allowed)?0:1;
if(dp[at][id]!=null) return dp[at][id];
pr curr;
if(allowed) {
int nodes = 1, minWt = graph.get(at).size();
for(int i: graph.get(at)) {
if(i == pt) continue;
pr pr = dfs(i, at, false);
nodes+=pr.freq;
minWt+=pr.wt;
}
curr = new pr(nodes, minWt);
} else {
int nodes = 0, minWt = 1;
for(int i: graph.get(at)) {
if(i == pt) continue;
pr prf = dfs(i, at, false);
pr prt = dfs(i, at, true);
pr cmp = compare(prf, prt);
nodes+=cmp.freq;
minWt+=cmp.wt;
}
curr = new pr(nodes, minWt);
}
return dp[at][id] = curr;
}
static void reconstructDfs(int at, int pt, boolean allowed) {
if(allowed) {
weights[at] = graph.get(at).size();
for(int i: graph.get(at)) {
if(i == pt) continue;
reconstructDfs(i, at, false);
}
} else {
weights[at] = 1;
for(int i: graph.get(at)) {
if(i == pt) continue;
pr prt = dp[i][0];
pr prf = dp[i][1];
pr cmp = compare(prt, prf);
reconstructDfs(i, at, cmp == prt);
}
}
}
static void solve() throws IOException {
int n = sc.ni();
graph = new ArrayList<>();
dp = new pr[n+1][2];
weights = new int[n+1];
for(int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}
for(int i = 0; i < n-1; i++) {
int from = sc.ni(), to = sc.ni();
graph.get(from).add(to);
graph.get(to).add(from);
}
if(n == 2) {
w.p("2 2");
w.p("1 1");
return;
}
pr anst = dfs(1, -1, true);
pr ansf = dfs(1, -1, false);
pr ans = compare(anst, ansf);
if(ans == anst) {
reconstructDfs(1, -1, true);
} else reconstructDfs(1, -1, false);
w.p(ans.freq+" "+ans.wt);
for(int i = 1; i <= n; i++) {
w.pr(weights[i]+" ");
}
w.pl();
}
static class pr {
int freq;
int wt;
public pr(int freq, int wt) {
this.freq = freq;
this.wt = wt;
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 2f32646b0c141de55818576fe0c490e5 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.util.*;
import java.io.*;
public class D_Weight_the_Tree{
public static void solve(int a[],int n,int m){
}
public static void main(String args[])throws IOException{
Reader sc=new Reader();
int n=sc.nextInt();
Graph g=new Graph(n);
for(int i=0;i<n-1;i++)
{
int u=sc.nextInt();
int v=sc.nextInt();
g.addEdge(u, v,0);
}
g.solve();
}
public static <K,V> Map<K,V> getLimitedSizedCache(int size){
/*Returns an unlimited sized map*/
if(size==0){
return (LinkedHashMap<K, V>) Collections.synchronizedMap(new LinkedHashMap<K, V>());
}
/*Returns the map with the limited size*/
Map<K, V> linkedHashMap = Collections.synchronizedMap(new LinkedHashMap<K, V>() {
protected boolean removeEldestEntry(Map.Entry<K, V> eldest)
{
return size() > size;
}
});
return linkedHashMap;
}
}
class BinarySearch<T extends Comparable<T>> {
T ele[];
int n;
public BinarySearch(T ele[],int n){
this.ele=(T[]) ele;
Arrays.sort(this.ele);
this.n=n;
}
public int lower_bound(T x){
//Return next smallest element greater than ewqual to the current element
int left=0;
int right=n-1;
while(left<=right){
int mid=left+(right-left)/2;
if(x.compareTo(ele[mid])==0)return mid;
if(x.compareTo(ele[mid])>0)left=mid+1;
else right=mid-1;
}
if(left ==n)return -1;
return left;
}
public int upper_bound(T x){
//Returns the highest element lss than equal to the current element
int left=0;
int right=n-1;
while(left<=right){
int mid=left+(right-left)/2;
if(x.compareTo(ele[mid])==0)return mid;
if(x.compareTo(ele[mid])>0)left=mid+1;
else right=mid-1;
}
return right;
}
}
class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[1000000]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
class Data implements Comparable<Data>{
int good_count,max_sum;
public Data(int gd,int ms){
this.good_count=gd;
this.max_sum=ms;
}
public int compareTo(Data o){
return 0;
}
public boolean equals(Data oth){
if(good_count==oth.good_count&&max_sum==oth.max_sum)return true;
return false;
}
public String toString(){
return good_count+" "+max_sum;
}
}
class Binary{
public String convertToBinaryString(long ele){
StringBuffer res=new StringBuffer();
while(ele>0){
if(ele%2==0)res.append(0+"");
else res.append(1+"");
ele=ele/2;
}
return res.reverse().toString();
}
}
class FenwickTree{
int bit[];
int size;
FenwickTree(int n){
this.size=n;
bit=new int[size];
}
public void modify(int index,int value){
while(index<size){
bit[index]+=value;
index=(index|(index+1));
}
}
public int get(int index){
int ans=0;
while(index>=0){
ans+=bit[index];
index=(index&(index+1))-1;
}
return ans;
}
}
class PAndC{
long c[][];
long mod;
public PAndC(int n,long mod){
c=new long[n+1][n+1];
this.mod=mod;
build(n);
}
public void build(int n){
for(int i=0;i<=n;i++){
c[i][0]=1;
c[i][i]=1;
for(int j=1;j<i;j++){
c[i][j]=(c[i-1][j]+c[i-1][j-1])%mod;
}
}
}
}
class Trie{
int trie[][];
int revind[];
int root[];
int tind,n;
int sz[];
int drev[];
public Trie(){
trie=new int[1000000][2];
root=new int[600000];
sz=new int[1000000];
tind=0;
n=0;
revind=new int[1000000];
drev=new int[20];
}
public void add(int ele){
// System.out.println(root[n]+" ");
n++;
tind++;
revind[tind]=n;
root[n]=tind;
addimpl(root[n-1],root[n],ele);
}
public void addimpl(int prev_root,int cur_root,int ele){
for(int i=18;i>=0;i--){
int edge=(ele&(1<<i))>0?1:0;
trie[cur_root][1-edge]=trie[prev_root][1-edge];
sz[cur_root]=sz[trie[cur_root][1-edge]];
tind++;
drev[i]=cur_root;
revind[tind]=n;
trie[cur_root][edge]=tind;
cur_root=tind;
prev_root=trie[prev_root][edge];
}
sz[cur_root]+=sz[prev_root]+1;
for(int i=0;i<=18;i++){
sz[drev[i]]=sz[trie[drev[i]][0]]+sz[trie[drev[i]][1]];
}
}
public void findmaxxor(int l,int r,int x){
int ans=0;
int cur_root=root[r];
for(int i=18;i>=0;i--){
int edge=(x&(1<<i))>0?1:0;
if(revind[trie[cur_root][1-edge]]>=l){
cur_root=trie[cur_root][1-edge];
ans+=(1-edge)*(1<<i);
}else{
cur_root=trie[cur_root][edge];
ans+=(edge)*(1<<i);
}
}
System.out.println(ans);
}
public void findKthStatistic(int l,int r,int k){
//System.out.println("In 3");
int curr=root[r];
int curl=root[l-1];
int ans=0;
for(int i=18;i>=0;i--){
for(int j=0;j<2;j++){
if(sz[trie[curr][j]]-sz[trie[curl][j]]<k)
k-=sz[trie[curr][j]]-sz[trie[curl][j]];
else{
curr=trie[curr][j];
curl=trie[curl][j];
ans+=(j)*(1<<i);
break;
}
}
}
System.out.println(ans);
}
public void findSmallest(int l,int r,int x){
//System.out.println("In 4");
int curr=root[r];
int curl=root[l-1];
int countl=0,countr=0;
// System.out.println(curl+" "+curr);
for(int i=18;i>=0;i--){
int edge=(x&(1<<i))>0?1:0;
// System.out.println(trie[curl][edge]+" "+trie[curr][edge]+" "+sz[curl]+" "+sz[curr]);
if(edge==1){
countr+=sz[trie[curr][0]];
countl+=sz[trie[curl][0]];
}
curr=trie[curr][edge];
curl=trie[curl][edge];
}
countl+=sz[curl];
countr+=sz[curr];
System.out.println(countr-countl);
}
}
class Printer{
public <T> T printArray(T obj[] ,String details){
System.out.println(details);
for(int i=0;i<obj.length;i++)
System.out.print(obj[i]+" ");
System.out.println();
return obj[0];
}
public <T> void print(T obj,String details){
System.out.println(details+" "+obj);
}
}
class Node{
long weight;
int vertex;
public Node(int vertex,long weight){
this.vertex=vertex;
this.weight=weight;
}
public String toString(){
return vertex+" "+weight;
}
}
class Graph{
int nv; //0 indexing i.e vertices starts from 0 input as 1 indexed for add Edge
List<List<Node>> adj;
boolean visited[];
Integer[] is_good;
Data dp[][];
public Graph(int n){
adj=new ArrayList<>();
this.nv=n;
is_good=new Integer[nv];
dp=new Data[nv+1][2];
// visited=new boolean[nv];
for(int i=0;i<n;i++)
adj.add(new ArrayList<Node>());
}
public void addEdge(int u,int v,long weight){
u--;v--;
Node first=new Node(v,weight);
Node second=new Node(u,weight);
adj.get(v).add(second);
adj.get(u).add(first);
}
// public void dfscheck(int u,long curweight){
// visited[u]=true;
// for(Node i:adj.get(u)){
// if(visited[i.vertex]==false&&(i.weight|curweight)==curweight)
// dfscheck(i.vertex,curweight);
// }
// }
long maxweight;
public void clear(){
this.adj=null;
this.nv=0;
}
public Data f(int vertex,int good,int parent){
if(dp[vertex][good]!=null){return dp[vertex][good];}
Data result=new Data(good,1);
result.max_sum = good==1?adj.get(vertex).size():1;
// System.out.println(adj.get(vertex));
for(Node i:adj.get(vertex)){
if(i.vertex!=parent){
Data temp=f(i.vertex,0,vertex);
if(good==0){
temp=Max(f(i.vertex,1,vertex),temp);
}
result.good_count+=temp.good_count;
result.max_sum+=temp.max_sum;
// System.out.println(temp);
}
}
// System.out.println(vertex+" "+good+" "+parent+" "+result);
dp[vertex][good]=result;
return result;
}
public Data Max(Data first,Data second){
if(first.good_count==second.good_count){
if(first.max_sum<second.max_sum)return first;
return second;
}
return first.good_count>second.good_count?first:second;
}
public void build(int vertex,Data res,int parent){
if(res.equals(f(vertex,0,parent))){
is_good[vertex]=0;
for(Node i:adj.get(vertex)){
if(i.vertex!=parent)
build(i.vertex,Max(f(i.vertex,0,vertex),f(i.vertex,1,vertex)),vertex);
}
}
else{
is_good[vertex]=1;
for(Node i:adj.get(vertex)){
if(i.vertex!=parent){
build(i.vertex,f(i.vertex,0,vertex),vertex);
}
}
}
}
public void solve() {
if(nv==2){
System.out.println("2 2\n 1 1");return;
}
Data res=Max(f(0,0,-1),f(0,1,-1));
System.out.println(res.good_count+" "+res.max_sum);
// Printer print=new Printer();
build(0,res,-1);
//print.printArray(is_good,"Is Good Array ");
StringBuffer res1=new StringBuffer();
for(int i=0;i<nv;i++){
if(is_good[i]==0){
res1.append(1+" ");
}else{
res1.append(adj.get(i).size()+" ");
}
}
System.out.println(res1);
}
// public void dfsutil(int msb){
// if(msb<0)return;
// maxweight-=(1l<<msb);
// visited=new boolean[nv];
// dfscheck(0,maxweight);
// for(int i=0;i<nv;i++)
// {
// if(visited[i]==false)
// {maxweight+=(1<<msb);
// break;}
// }
// dfsutil(msb-1);
// }
// public boolean TopologicalSort() {
// top=new int[nv];
// int cnt=0;
// int indegree[]=new int[nv];
// for(int i=0;i<nv;i++){
// for(int j:adj.get(i)){
// indegree[j]++;
// }
// }
// Deque<Integer> q=new LinkedList<Integer>();
// for(int i=0;i<nv;i++){
// if(indegree[i]==0){
// q.addLast(i);
// }
// }
// while(q.size()>0){
// int tele=q.pop();
// top[tele]=cnt++;
// for(int j:adj.get(tele)){
// indegree[j]--;
// if(indegree[j]==0)
// q.addLast(j);
// }
// }
// return cnt==nv;
// }
// public boolean isBipartiteGraph(){
// col=new Integer[nv];
// visited=new boolean[nv];
// for(int i=0;i<nv;i++){
// if(visited[i]==false){
// col[i]=0;
// dfs(i);
// }
// }
}
class DSU{
int []parent;
int rank[];
int n;
public DSU(int n){
this.n=n;
parent=new int[n];
rank=new int[n];
for(int i=0;i<n;i++)
{ parent[i]=i;
rank[i]=1;
}
}
public int find(int i){
if(parent[i]==i)return i;
return parent[i]=find(parent[i]);
}
public boolean union(int a,int b){
int pa=find(a);
int pb=find(b);
if(pa==pb)return false;
if(rank[pa]>rank[pb]){
parent[pb]=pa;
rank[pa]+=rank[pb];
}
else{
parent[pa]=pb;
rank[pb]+=rank[pa];
}
return true;
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | f3912a9d503c3f388be0c3edd6ad86f7 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | //make sure to make new file!
import java.io.*;
import java.util.*;
public class D774c{
public static ArrayList<ArrayList<Integer>> adj;
public static int[][] dp;
public static long[][] dpsum;
public static ArrayList<ArrayList<Integer>> paradj;
public static int[] answer;
public static void main(String[] args)throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
adj = new ArrayList<ArrayList<Integer>>(n+1);
for(int k = 0; k <= n; k++) adj.add(new ArrayList<Integer>());
for(int k = 0; k < n-1; k++){
st = new StringTokenizer(f.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
adj.get(a).add(b);
adj.get(b).add(a);
}
if(n==2){
out.println("2 2");
out.println("1 1");
out.close();
return;
}
paradj = new ArrayList<ArrayList<Integer>>(2*n+1); //v*2-1 for 0, v*2 for 1
for(int k = 0; k <= 2*n; k++) paradj.add(new ArrayList<Integer>());
dp = new int[n+1][2];
dpsum = new long[n+1][2];
dfs(1,-1);
int startnode;
if(dp[1][1] > dp[1][0] || (dp[1][1] == dp[1][0] && dpsum[1][1] < dpsum[1][0])){
startnode = 2;
out.println(dp[1][1] + " " + dpsum[1][1]);
} else {
startnode = 1;
out.println(dp[1][0] + " " + dpsum[1][0]);
}
answer = new int[n+1];
backtrack(startnode);
StringJoiner sj = new StringJoiner(" ");
for(int k = 1; k <= n; k++){
sj.add("" + answer[k]);
}
out.println(sj.toString());
out.close();
}
public static void backtrack(int v){
if(v%2 == 1){
//use
answer[(v+1)/2] = adj.get((v+1)/2).size();
} else {
//sacrificial lamb
answer[v/2] = 1;
}
for(int nei : paradj.get(v)){
//should only be one
backtrack(nei);
}
}
public static void dfs(int v, int p){
dp[v][0] = 1;
dp[v][1] = 0;
dpsum[v][0] = (long)adj.get(v).size();
dpsum[v][1] = 1L;
for(int nei : adj.get(v)){
if(nei == p)
continue;
dfs(nei,v);
dp[v][0] += dp[nei][1];
dpsum[v][0] += dpsum[nei][1];
paradj.get(2*v-1).add(2*nei);
if(dp[nei][0] > dp[nei][1] || (dp[nei][0] == dp[nei][1] && dpsum[nei][0] < dpsum[nei][1])){
//use 0
dp[v][1] += dp[nei][0];
dpsum[v][1] += dpsum[nei][0];
paradj.get(2*v).add(2*nei-1);
} else {
//use 1
dp[v][1] += dp[nei][1];
dpsum[v][1] += dpsum[nei][1];
paradj.get(2*v).add(2*nei);
}
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 529fcbb683dd4ef095c381446ad29c98 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.math.BigInteger;
public final class A
{
static PrintWriter out = new PrintWriter(System.out);
static StringBuilder ans=new StringBuilder();
static FastReader in=new FastReader();
// static int g[][];
static ArrayList<Integer> g[];
static long mod=(long) 998244353,INF=Long.MAX_VALUE;
static boolean set[];
static int max=0;
static int lca[][];
static int par[],col[],D[];
static long fact[];
static int size[],N;
static long dp[][],sum[][],f[];
static ArrayList [] seg;
public static void main(String args[])throws IOException
{
/*
* star,rope,TPST
* BS,LST,MS,MQ
*/
int N=i();
g=new ArrayList[N+1];
for(int i=0; i<=N; i++)g[i]=new ArrayList<>();
int deg[]=new int[N+1];
int root=1;
for(int i=1; i<N; i++)
{
int a=i(),b=i();
g[a].add(b);
g[b].add(a);
deg[a]++;
deg[b]++;
if(deg[a]>=2)root=a;
if(deg[b]>=2)root=b;
}
dp=new long[N+1][2];
sum=new long[N+1][2];
if(N==2)
{
ans.append("2 2\n");
ans.append("1 1\n");
}
else
{
f(root,-1);
//print(dp);
// print(sum);
// print(dp[1]);
// print(sum[1]);
f=new long[N+1];
//root=1;
long leaf=0,sum12=0;
// System.out.println(dp[root][0]+" "+dp[root][1]+" "+sum[root][0]+" "+sum[root][1]);
if(dp[root][1]>dp[root][0])
{
leaf=dp[root][1];
sum12=sum[root][1];
f2(root,-1,false);
}
else if(dp[root][1]<dp[root][0])
{
//System.out.println("run");
leaf=dp[root][0];
sum12=sum[root][0];
f2(root,-1,true);
}
else
{
leaf=dp[root][0];
sum12=Math.min(sum[root][1], sum[root][0]);
if(sum[root][1]<=sum[root][0])
f2(root,-1,false);
else f2(root,-1,true);
}
ans.append(leaf+" "+sum12+"\n");
for(int i=1; i<=N; i++)ans.append(f[i]+" ");
}
out.print(ans);
out.close();
}
// static void dfs(int N,int p)
// {
//
// }
static void f2(int n,int p,boolean good)
{
boolean isLeaf=true;
for(int c:g[n])
{
if(c!=p)
{
isLeaf=false;
}
}
if(isLeaf)
{
f[n]=1;
return;
}
if(good)
{
f[n]=g[n].size();
for(int c:g[n])
{
if(c!=p)
f2(c,n,false);
}
}
else
{
f[n]=1;
for(int c:g[n])
{
if(c!=p)
{
if(dp[c][1]==dp[c][0])
{
if(sum[c][1]>=sum[c][0])
{
f2(c,n,true);
}
else f2(c,n,false);
}
else if(dp[c][0]>dp[c][1])
{
f2(c,n,true);
}
else
{
f2(c,n,false);
}
}
}
}
}
static void f(int n,int p)
{
// boolean isLeaf=true;
// for(int c:g[n])
// {
// if(c!=p)
// {
// isLeaf=false;
// }
// }
// if(isLeaf)
// {
// sum[n][0]=1;
// sum[n][1]=1;
// dp[n][0]=1;
// dp[n][1]=1;
// return;
// }
dp[n][0]=1;//0 means is good
dp[n][1]=0;
sum[n][0]=g[n].size();
sum[n][1]=1;
for(int c:g[n])
{
if(c!=p)
{
f(c,n);
dp[n][0]+=dp[c][1];
sum[n][0]+=sum[c][1];
dp[n][1]+=Math.max(dp[c][1], dp[c][0]);
if(dp[c][1]==dp[c][0])
{
sum[n][1]+=Math.min(sum[c][0], sum[c][1]);
}
else if(dp[c][1]>dp[c][0])
{
sum[n][1]+=sum[c][1];
}
else
{
sum[n][1]+=sum[c][0];
}
}
}
}
static int count(long N)
{
int cnt=0;
long p=1L;
while(p<=N)
{
if((p&N)!=0)cnt++;
p<<=1;
}
return cnt;
}
static long kadane(long A[])
{
long lsum=A[0],gsum=0;
gsum=Math.max(gsum, lsum);
for(int i=1; i<A.length; i++)
{
lsum=Math.max(lsum+A[i],A[i]);
gsum=Math.max(gsum,lsum);
}
return gsum;
}
public static boolean pal(int i)
{
StringBuilder sb=new StringBuilder();
StringBuilder rev=new StringBuilder();
int p=1;
while(p<=i)
{
if((i&p)!=0)
{
sb.append("1");
}
else sb.append("0");
p<<=1;
}
rev=new StringBuilder(sb.toString());
rev.reverse();
if(i==8)System.out.println(sb+" "+rev);
return (sb.toString()).equals(rev.toString());
}
public static void reverse(int i,int j,int A[])
{
while(i<j)
{
int t=A[i];
A[i]=A[j];
A[j]=t;
i++;
j--;
}
}
public static int ask(int a,int b,int c)
{
System.out.println("? "+a+" "+b+" "+c);
return i();
}
static int[] reverse(int A[],int N)
{
int B[]=new int[N];
for(int i=N-1; i>=0; i--)
{
B[N-i-1]=A[i];
}
return B;
}
static boolean isPalin(char X[])
{
int i=0,j=X.length-1;
while(i<=j)
{
if(X[i]!=X[j])return false;
i++;
j--;
}
return true;
}
static int distance(int a,int b)
{
int d=D[a]+D[b];
int l=LCA(a,b);
l=2*D[l];
return d-l;
}
static int LCA(int a,int b)
{
if(D[a]<D[b])
{
int t=a;
a=b;
b=t;
}
int d=D[a]-D[b];
int p=1;
for(int i=0; i>=0 && p<=d; i++)
{
if((p&d)!=0)
{
a=lca[a][i];
}
p<<=1;
}
if(a==b)return a;
for(int i=max-1; i>=0; i--)
{
if(lca[a][i]!=-1 && lca[a][i]!=lca[b][i])
{
a=lca[a][i];
b=lca[b][i];
}
}
return lca[a][0];
}
static void dfs(int n,int p)
{
lca[n][0]=p;
if(p!=-1)D[n]=D[p]+1;
for(int c:g[n])
{
if(c!=p)
{
dfs(c,n);
}
}
}
static int[] prefix_function(char X[])//returns pi(i) array
{
int N=X.length;
int pre[]=new int[N];
for(int i=1; i<N; i++)
{
int j=pre[i-1];
while(j>0 && X[i]!=X[j])
j=pre[j-1];
if(X[i]==X[j])j++;
pre[i]=j;
}
return pre;
}
static TreeNode start;
public static void f(TreeNode root,TreeNode p,int r)
{
if(root==null)return;
if(p!=null)
{
root.par=p;
}
if(root.val==r)start=root;
f(root.left,root,r);
f(root.right,root,r);
}
static int right(int A[],int Limit,int l,int r)
{
while(r-l>1)
{
int m=(l+r)/2;
if(A[m]<Limit)l=m;
else r=m;
}
return l;
}
static int left(int A[],int a,int l,int r)
{
while(r-l>1)
{
int m=(l+r)/2;
if(A[m]<a)l=m;
else r=m;
}
return l;
}
// static void build(int v,int tl,int tr,int A[])
// {
// if(tl==tr)
// {
// seg[v]=A[tl];
// return;
// }
// int tm=(tl+tr)/2;
// build(v*2,tl,tm,A);
// build(v*2+1,tm+1,tr,A);
// if((tm+1-tl)%2==0)
// seg[v]=seg[v*2]+seg[v*2+1];
// else seg[v]=seg[v*2]-seg[v*2+1];
// }
static void update(int v,int tl,int tr,int l,int r,int a)
{
if(l>r)return;
if(l==tl && tr==tr)
{
seg[v].add(a);
}
else
{
int tm=(tl+tr)/2;
update(v*2,tl,tm,l,Math.min(r, tm),a);
update(v*2+1,tm+1,tr,Math.max(tm+1, l),r,a);
}
}
// static void ask(int v,int tl,int tr,int index)
// {
//
// //if(l>r)return 0;
// if(tl==index && tl==tr)
// {
//
// }
// int tm=(tl+tr)/2;
//
// return ask(v*2,tl,tm,l,Math.min(tm, r))+ask(v*2+1,tm+1,tr,Math.max(tm+1, l),r);
// }
static boolean f(long A[],long m,int N)
{
long B[]=new long[N];
for(int i=0; i<N; i++)
{
B[i]=A[i];
}
for(int i=N-1; i>=0; i--)
{
if(B[i]<m)return false;
if(i>=2)
{
long extra=Math.min(B[i]-m, A[i]);
long x=extra/3L;
B[i-2]+=2L*x;
B[i-1]+=x;
}
}
return true;
}
static int f(int l,int r,long A[],long x)
{
while(r-l>1)
{
int m=(l+r)/2;
if(A[m]>=x)l=m;
else r=m;
}
return r;
}
static boolean f(long m,long H,long A[],int N)
{
long s=m;
for(int i=0; i<N-1;i++)
{
s+=Math.min(m, A[i+1]-A[i]);
}
return s>=H;
}
static long ask(long l,long r)
{
System.out.println("? "+l+" "+r);
return l();
}
static long f(long N,long M)
{
long s=0;
if(N%3==0)
{
N/=3;
s=N*M;
}
else
{
long b=N%3;
N/=3;
N++;
s=N*M;
N--;
long a=N*M;
if(M%3==0)
{
M/=3;
a+=(b*M);
}
else
{
M/=3;
M++;
a+=(b*M);
}
s=Math.min(s, a);
}
return s;
}
static int ask(StringBuilder sb,int a)
{
System.out.println(sb+""+a);
return i();
}
static void swap(char X[],int i,int j)
{
char x=X[i];
X[i]=X[j];
X[j]=x;
}
static int min(int a,int b,int c)
{
return Math.min(Math.min(a, b), c);
}
static long and(int i,int j)
{
System.out.println("and "+i+" "+j);
return l();
}
static long or(int i,int j)
{
System.out.println("or "+i+" "+j);
return l();
}
static int len=0,number=0;
static void f(char X[],int i,int num,int l)
{
if(i==X.length)
{
if(num==0)return;
//update our num
if(isPrime(num))return;
if(l<len)
{
len=l;
number=num;
}
return;
}
int a=X[i]-'0';
f(X,i+1,num*10+a,l+1);
f(X,i+1,num,l);
}
static boolean is_Sorted(int A[])
{
int N=A.length;
for(int i=1; i<=N; i++)if(A[i-1]!=i)return false;
return true;
}
static boolean f(StringBuilder sb,String Y,String order)
{
StringBuilder res=new StringBuilder(sb.toString());
HashSet<Character> set=new HashSet<>();
for(char ch:order.toCharArray())
{
set.add(ch);
for(int i=0; i<sb.length(); i++)
{
char x=sb.charAt(i);
if(set.contains(x))continue;
res.append(x);
}
}
String str=res.toString();
return str.equals(Y);
}
static boolean all_Zero(int f[])
{
for(int a:f)if(a!=0)return false;
return true;
}
static long form(int a,int l)
{
long x=0;
while(l-->0)
{
x*=10;
x+=a;
}
return x;
}
static int count(String X)
{
HashSet<Integer> set=new HashSet<>();
for(char x:X.toCharArray())set.add(x-'0');
return set.size();
}
static int f(long K)
{
long l=0,r=K;
while(r-l>1)
{
long m=(l+r)/2;
if(m*m<K)l=m;
else r=m;
}
return (int)l;
}
// static void build(int v,int tl,int tr,long A[])
// {
// if(tl==tr)
// {
// seg[v]=A[tl];
// }
// else
// {
// int tm=(tl+tr)/2;
// build(v*2,tl,tm,A);
// build(v*2+1,tm+1,tr,A);
// seg[v]=Math.min(seg[v*2], seg[v*2+1]);
// }
// }
static int [] sub(int A[],int B[])
{
int N=A.length;
int f[]=new int[N];
for(int i=N-1; i>=0; i--)
{
if(B[i]<A[i])
{
B[i]+=26;
B[i-1]-=1;
}
f[i]=B[i]-A[i];
}
for(int i=0; i<N; i++)
{
if(f[i]%2!=0)f[i+1]+=26;
f[i]/=2;
}
return f;
}
static int[] f(int N)
{
char X[]=in.next().toCharArray();
int A[]=new int[N];
for(int i=0; i<N; i++)A[i]=X[i]-'a';
return A;
}
static int max(int a ,int b,int c,int d)
{
a=Math.max(a, b);
c=Math.max(c,d);
return Math.max(a, c);
}
static int min(int a ,int b,int c,int d)
{
a=Math.min(a, b);
c=Math.min(c,d);
return Math.min(a, c);
}
static HashMap<Integer,Integer> Hash(int A[])
{
HashMap<Integer,Integer> mp=new HashMap<>();
for(int a:A)
{
int f=mp.getOrDefault(a,0)+1;
mp.put(a, f);
}
return mp;
}
static long mul(long a, long b)
{
return ( a %mod * 1L * b%mod )%mod;
}
static void swap(int A[],int a,int b)
{
int t=A[a];
A[a]=A[b];
A[b]=t;
}
static int find(int a)
{
if(par[a]<0)return a;
return par[a]=find(par[a]);
}
static void union(int a,int b)
{
a=find(a);
b=find(b);
if(a!=b)
{
if(par[a]>par[b]) //this means size of a is less than that of b
{
int t=b;
b=a;
a=t;
}
par[a]+=par[b];
par[b]=a;
}
}
static boolean isSorted(int A[])
{
for(int i=1; i<A.length; i++)
{
if(A[i]<A[i-1])return false;
}
return true;
}
static boolean isDivisible(StringBuilder X,int i,long num)
{
long r=0;
for(; i<X.length(); i++)
{
r=r*10+(X.charAt(i)-'0');
r=r%num;
}
return r==0;
}
static int lower_Bound(int A[],int low,int high, int x)
{
if (low > high)
if (x >= A[high])
return A[high];
int mid = (low + high) / 2;
if (A[mid] == x)
return A[mid];
if (mid > 0 && A[mid - 1] <= x && x < A[mid])
return A[mid - 1];
if (x < A[mid])
return lower_Bound( A, low, mid - 1, x);
return lower_Bound(A, mid + 1, high, x);
}
static String f(String A)
{
String X="";
for(int i=A.length()-1; i>=0; i--)
{
int c=A.charAt(i)-'0';
X+=(c+1)%2;
}
return X;
}
static void sort(long[] a) //check for long
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static String swap(String X,int i,int j)
{
char ch[]=X.toCharArray();
char a=ch[i];
ch[i]=ch[j];
ch[j]=a;
return new String(ch);
}
static int sD(long n)
{
if (n % 2 == 0 )
return 2;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0 )
return i;
}
return (int)n;
}
// static void setGraph(int N,int nodes)
// {
//// size=new int[N+1];
// par=new int[N+1];
// col=new int[N+1];
//// g=new int[N+1][];
// D=new int[N+1];
// int deg[]=new int[N+1];
// int A[][]=new int[nodes][2];
// for(int i=0; i<nodes; i++)
// {
// int a=i(),b=i();
// A[i][0]=a;
// A[i][1]=b;
// deg[a]++;
// deg[b]++;
// }
// for(int i=0; i<=N; i++)
// {
// g[i]=new int[deg[i]];
// deg[i]=0;
// }
// for(int a[]:A)
// {
// int x=a[0],y=a[1];
// g[x][deg[x]++]=y;
// g[y][deg[y]++]=x;
// }
// }
static long pow(long a,long b)
{
//long mod=1000000007;
long pow=1;
long x=a;
while(b!=0)
{
if((b&1)!=0)pow=(pow*x)%mod;
x=(x*x)%mod;
b/=2;
}
return pow;
}
static long toggleBits(long x)//one's complement || Toggle bits
{
int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1;
return ((1<<n)-1)^x;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static boolean isPrime(long 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;
}
static void print(char A[])
{
for(char c:A)System.out.print(c+" ");
System.out.println();
}
static void print(boolean A[])
{
for(boolean c:A)System.out.print(c+" ");
System.out.println();
}
static void print(int A[])
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static void print(long A[])
{
for(long i:A)System.out.print(i+ " ");
System.out.println();
}
static void print(boolean A[][])
{
for(boolean a[]:A)print(a);
}
static void print(long A[][])
{
for(long a[]:A)print(a);
}
static void print(int A[][])
{
for(int a[]:A)print(a);
}
static void print(ArrayList<Integer> A)
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static int i()
{
return in.nextInt();
}
static long l()
{
return in.nextLong();
}
static int[] input(int N){
int A[]=new int[N];
for(int i=0; i<N; i++)
{
A[i]=in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[]=new long[N];
for(int i=0; i<A.length; i++)A[i]=in.nextLong();
return A;
}
static long GCD(long a,long b)
{
if(b==0)
{
return a;
}
else return GCD(b,a%b );
}
}
class segNode
{
long pref,suff,sum,max;
segNode(long a,long b,long c,long d)
{
pref=a;
suff=b;
sum=c;
max=d;
}
}
//class TreeNode
//{
// int cnt,index;
// TreeNode left,right;
// TreeNode(int c)
// {
// cnt=c;
// index=-1;
// }
// TreeNode(int c,int index)
// {
// cnt=c;
// this.index=index;
// }
//}
class role
{
String skill;
int level;
role(String s,int l)
{
skill=s;
level=l;
}
}
class project implements Comparable<project>
{
int score,index;
project(int s,int i)
{
// roles=r;
index=i;
score=s;
// skill=new String[r];
// lvl=new int[r];
}
public int compareTo(project x)
{
return x.score-this.score;
}
}
class post implements Comparable<post>
{
long x,y,d,t;
post(long a,long b,long c)
{
x=a;
y=b;
d=c;
}
public int compareTo(post X)
{
if(X.t==this.t)
{
return 0;
}
else
{
long xt=this.t-X.t;
if(xt>0)return 1;
return -1;
}
}
}
class TreeNode
{
int val;
TreeNode left, right,par;
TreeNode() {}
TreeNode(int item)
{
val = item;
left =null;
right = null;
par=null;
}
}
class edge
{
int a,wt;
edge(int a,int w)
{
this.a=a;
wt=w;
}
}
class pair3 implements Comparable<pair3>
{
long a;
int index;
pair3(long x,int i)
{
a=x;
index=i;
}
public int compareTo(pair3 x)
{
return this.index-x.index;
}
}
//Code For FastReader
//Code For FastReader
//Code For FastReader
//Code For FastReader
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while(st==null || !st.hasMoreElements())
{
try
{
st=new StringTokenizer(br.readLine());
}
catch(IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | fc9748495d9252fba7fc0a4eaa9d5d27 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.util.*;
import java.io.*;
// BEFORE 31ST MARCH 2022 !!
//MAX RATING EVER ACHIEVED-1622(LETS SEE WHEN WILL I GET TO CHANGE THIS)
////***************************************************************************
/* public class E_Gardener_and_Tree implements Runnable{
public static void main(String[] args) throws Exception {
new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start();
}
public void run(){
WRITE YOUR CODE HERE!!!!
JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!!
}
}
*/
/////**************************************************************************
public class D_Weight_the_Tree{
public static void main(String[] args) {
FastScanner s= new FastScanner();
//PrintWriter out=new PrintWriter(System.out);
//end of program
//out.println(answer);
//out.close();
StringBuilder res = new StringBuilder();
int n=s.nextInt();
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(n+3);
for(int i=0;i<=n;i++){
ArrayList<Integer> obj1 = new ArrayList<Integer>();
list.add(obj1);
}
for(int i=0;i<n-1;i++){
int a=s.nextInt();
int b=s.nextInt();
list.get(a).add(b);
list.get(b).add(a);
}
if(n==2){
res.append("2 2 \n");
res.append("1 1 \n");
System.out.println(res);
return;
}
long dp1[][]=new long[n+1][2];//0=> means not special
//1=> mean special
//stores the max num of secial nodes in the subtree of i
long dp2[][]= new long[n+1][2];
//stores the min sum of the subtree of i
dfs1(list,dp1,dp2,1,0);
long nice[]= new long[n+1];
long count[]= new long[1];
if(dp1[1][1]>dp1[1][0]){
dfs2(list,nice,count,1,0,1,dp1,dp2);
}
else if(dp1[1][0]>dp1[1][1]){
dfs2(list,nice,count,1,0,0,dp1,dp2);
}
else{
if(dp2[1][1]<dp2[1][0]){
dfs2(list,nice,count,1,0,1,dp1,dp2);
}
else{
dfs2(list,nice,count,1,0,0,dp1,dp2);
}
}
long sum=0;
for(int i=1;i<=n;i++){
sum+=nice[i];
}
res.append(count[0]+" "+sum+" \n");
for(int i=1;i<=n;i++){
res.append(nice[i]+" ");
}
res.append(" \n");
System.out.println(res);
}
private static void dfs2(ArrayList<ArrayList<Integer>> list, long[] nice, long[] count, int i, int parent, int state,long dp1[][],long dp2[][]) {
if(state==1){
count[0]++;
nice[i]=list.get(i).size();
for(int j=0;j<list.get(i).size();j++){
int num=list.get(i).get(j);
if(num!=parent){
dfs2(list,nice,count,num,i,0,dp1,dp2);
}
}
}
else{
nice[i]=1;
for(int j=0;j<list.get(i).size();j++){
int num=list.get(i).get(j);
if(num!=parent){
if(dp1[num][1]>dp1[num][0]){
dfs2(list,nice,count,num,i,1,dp1,dp2);
}
else if(dp1[num][0]>dp1[num][1]){
dfs2(list,nice,count,num,i,0,dp1,dp2);
}
else{
if(dp2[num][1]<dp2[num][0]){
dfs2(list,nice,count,num,i,1,dp1,dp2);
}
else{
dfs2(list,nice,count,num,i,0,dp1,dp2);
}
}
}
}
}
}
private static void dfs1(ArrayList<ArrayList<Integer>> list, long[][] dp1, long[][] dp2, int i, int parent) {
for(int j=0;j<list.get(i).size();j++){
int num=list.get(i).get(j);
if(num!=parent){
dfs1(list,dp1,dp2,num,i);
}
}
{
//considering i as special
long alpha=0;
long beta=0;
for(int j=0;j<list.get(i).size();j++){
int num=list.get(i).get(j);
if(num!=parent){
alpha+=dp1[num][0];
beta+=dp2[num][0];
}
}
alpha++;
beta+=list.get(i).size();
dp1[i][1]=alpha;
dp2[i][1]=beta;
}
{
//not considering i as special
long alpha=0;
long beta=0;
for(int j=0;j<list.get(i).size();j++){
int num=list.get(i).get(j);
if(num!=parent){
if(dp1[num][1]>dp1[num][0]){
alpha+=dp1[num][1];
beta+=dp2[num][1];
}
else if(dp1[num][0]>dp1[num][1]){
alpha+=dp1[num][0];
beta+=dp2[num][0];
}
else{
if(dp2[num][1]<dp2[num][0]){
alpha+=dp1[num][1];
beta+=dp2[num][1];
}
else{
alpha+=dp1[num][0];
beta+=dp2[num][0];
}
}
}
}
beta++;
dp1[i][0]=alpha;
dp2[i][0]=beta;
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
static long modpower(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// SIMPLE POWER FUNCTION=>
static long power(long x, long y)
{
long res = 1; // Initialize result
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = res * x;
// y must be even now
y = y >> 1; // y = y/2
x = x * x; // Change x to x^2
}
return res;
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 8c3875183cb6af7f94e651f4e0af14e8 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int[][] edges = new int[n - 1][2];
for (int i = 0; i < n - 1; i++) {
edges[i][0] = cin.nextInt() - 1;
edges[i][1] = cin.nextInt() - 1;
}
new Solution().func(edges);
}
}
class Solution {
Set<Integer>[] sets;
int[][] goodNums;
int[][] sumWeights;
int[] good;
int[] weights;
public void func(int[][] edges) {
int n = edges.length + 1;
if (n == 2) {
System.out.println("2 2\n1 1");
return;
}
goodNums = new int[n][2];
sumWeights = new int[n][2];
good = new int[n];
sets = new Set[n];
weights = new int[n];
for (int i = 0; i < sets.length; i++) {
sets[i] = new HashSet<>();
}
for (int[] edge : edges) {
sets[edge[0]].add(edge[1]);
sets[edge[1]].add(edge[0]);
}
dfs(0, 0);
int b = choice(0);
dfs2(0, b, 0);
System.out.println(goodNums[0][b] + " " + sumWeights[0][b]);
StringBuilder sb = new StringBuilder();
for (int weight : weights) {
sb.append(weight);
sb.append(' ');
}
System.out.println(sb);
}
private int choice(int v) {
if (goodNums[v][0] > goodNums[v][1]) {
return 0;
} else if (goodNums[v][0] < goodNums[v][1]) {
return 1;
} else {
return sumWeights[v][0] <= sumWeights[v][1] ? 0 : 1;
}
}
private void dfs2(int node, int b, int p) {
if (b == 1) {
weights[node] = sets[node].size();
} else {
weights[node] = 1;
}
for (Integer v : sets[node]) {
if (v == p) {
continue;
}
dfs2(v, b == 1 ? 0 : good[v], node);
}
}
private void dfs(int node, int p) {
goodNums[node][1] = 1;
sumWeights[node][0] = 1;
sumWeights[node][1] = sets[node].size();
for (Integer v : sets[node]) {
if (v == p) {
continue;
}
dfs(v, node);
int b = choice(v);
goodNums[node][0] += goodNums[v][b];
sumWeights[node][0] += sumWeights[v][b];
good[v] = b;
goodNums[node][1] += goodNums[v][0];
sumWeights[node][1] += sumWeights[v][0];
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 46a6e4f5fbe9c672ada3255aef75dbaf | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import javafx.util.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(
new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
buf[cnt++] = (byte)c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0,
BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
static int parent(int a , int p[])
{
if(a == p[a])
return a;
return p[a] = parent(p[a],p);
}
static void union(int a , int b , int p[] , int sz[])
{
a = parent(a,p);
b = parent(b,p);
if(a == b)
return;
if(sz[a] < sz[b])
{
int tmp = a;
a = b;
b = tmp;
}
p[b] = a;
sz[a] += sz[b];
}
static long pow(long a , long b , long c)
{
if(b == 0)
return 1;
long ans = pow(a,b/2,c);
if(b%2 == 0)
return ans*ans%c;
return ans*ans%c*a%c;
}
static long st[];
static long lazy[];
static int sz;
static void setMax(int l , int r , long v , int lx , int rx , int x)
{
if(lazy[x] != Long.MIN_VALUE)
{
st[x] = Math.max(st[x],lazy[x]);
if(lx != rx)
{
lazy[2*x+1] = Math.max(lazy[2*x+1],lazy[x]);
lazy[2*x+2] = Math.max(lazy[2*x+2],lazy[x]);
}
lazy[x] = Long.MIN_VALUE;
}
if(lx > r || rx < l)
return;
if(lx >= l && rx <= r)
{
st[x] = Math.max(st[x],v);
if(lx != rx)
{
lazy[2*x+1] = Math.max(lazy[2*x+1],v);
lazy[2*x+2] = Math.max(lazy[2*x+2],v);
}
return;
}
int mid = (lx+rx)/2;
setMax(l,r,v,lx,mid,2*x+1);
setMax(l,r,v,mid+1,rx,2*x+2);
st[x] = Math.max(st[2*x+1],st[2*x+2]);
}
static long getMax(int l , int r , int lx , int rx , int x)
{
if(lazy[x] != Long.MIN_VALUE)
{
st[x] = Math.max(st[x],lazy[x]);
if(lx != rx)
{
lazy[2*x+1] = Math.max(lazy[2*x+1],lazy[x]);
lazy[2*x+2] = Math.max(lazy[2*x+2],lazy[x]);
}
lazy[x] = Long.MIN_VALUE;
}
if(lx > r || rx < l)
return -1000000000000000L;
if(lx >= l && rx <= r)
return st[x];
int mid = (lx+rx)/2;
return Math.max(getMax(l,r,lx,mid,2*x+1),getMax(l,r,mid+1,rx,2*x+2));
}
static boolean check(int x , int a[] , int b[] , int g[][] , long s , int k)
{
long aa = Long.MAX_VALUE;
long bb = Long.MAX_VALUE;
for(int i = 1 ; i <= x ; i++)
{
aa = Math.min(aa,a[i]);
bb = Math.min(bb,b[i]);
}
long cost[] = new long[g.length];
for(int i = 0 ; i < g.length ; i++)
{
if(g[i][0] == 1)
cost[i] = aa*(long)g[i][1];
else
cost[i] = bb*(long)g[i][1];
}
Arrays.sort(cost);
for(int i = 0 ; i < k ; i++)
{
s -= cost[i];
if(s < 0)
return false;
}
return true;
}
public static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
static void dfs(int n , ArrayList<Integer> arr[] , int p , int dp1[][] , long dp2[][])
{
dp1[n][0] = 1;
dp2[n][0] = arr[n].size();
dp2[n][1] = 1;
for(Integer v : arr[n])
{
if(v != p)
{
dfs(v,arr,n,dp1,dp2);
dp1[n][0] += dp1[v][1];
dp1[n][1] += Math.max(dp1[v][0],dp1[v][1]);
dp2[n][0] += dp2[v][1];
if(dp1[v][0] > dp1[v][1])
{
dp2[n][1] += dp2[v][0];
}
else if(dp1[v][1] > dp1[v][0])
{
dp2[n][1] += dp2[v][1];
}
else
{
dp2[n][1] += Math.min(dp2[v][0],dp2[v][1]);
}
}
}
}
static void dfs2(int n , ArrayList<Integer> arr[] , int p , int dp1[][] , long dp2[][],
long ans[] , int last)
{
if(last == 0)
{
ans[n] = 1;
for(Integer v : arr[n])
{
if(v != p)
{
dfs2(v,arr,n,dp1,dp2,ans,1);
}
}
return;
}
int fn = -1;
if(dp1[n][0] > dp1[n][1])
fn = 0;
else if(dp1[n][1] > dp1[n][0])
fn = 1;
else
{
if(dp2[n][0] < dp2[n][1])
fn = 0;
else
fn = 1;
}
if(fn == 0)
ans[n] = arr[n].size();
else
ans[n] = 1;
for(Integer v : arr[n])
{
if(v != p)
{
dfs2(v,arr,n,dp1,dp2,ans,fn);
}
}
}
public static void main(String []args) throws IOException
{
Reader sc = new Reader();
int n = sc.nextInt();
ArrayList<Integer> arr[] = new ArrayList[n];
for(int i = 0 ; i < n ; i++)
{
arr[i] = new ArrayList<Integer>();
}
for(int i = 0 ; i < n-1 ; i++)
{
int x = sc.nextInt()-1;
int y = sc.nextInt()-1;
arr[x].add(y);
arr[y].add(x);
}
if(n == 2)
{
System.out.println(2 + " " + 2);
System.out.println(1 + " " + 1);
}
else
{
int dp1[][] = new int[n][2];
long dp2[][] = new long[n][2];
dfs(0,arr,-1,dp1,dp2);
long ans[] = new long[n];
dfs2(0,arr,-1,dp1,dp2,ans,1);
StringBuffer str = new StringBuffer("");
long tot = 0;
for(int i = 0 ; i < n ; i++)
{
tot += ans[i];
}
System.out.println((Math.max(dp1[0][0],dp1[0][1])) + " " + tot);
for(int i = 0 ; i < n ; i++)
{
str.append(ans[i] + " ");
}
System.out.println(str);
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output | |
PASSED | 4cbf07750287865292e86480a093a507 | train_110.jsonl | 1646408100 | You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$. A tree is a connected undirected graph without cycles. For each $$$i=1,2, \ldots, n$$$, let $$$w_i$$$ be the weight of the $$$i$$$-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree. | 256 megabytes | import java.util.*;
import java.util.Map.Entry;
import java.math.*;
import java.io.*;
public class Main {
public static Node[] dpSpe;
public static Node[] dpNotSpe;
public static List<List<Integer>> g;
public static List<List<Integer>> tree;
public static int[] numEdges;
public static int[] weight;
public static void main(String[] args) throws FileNotFoundException {
InputReader in = new InputReader(System.in);
// Scanner in = new Scanner(System.in);
// Scanner in = new Scanner(new BufferedReader(new
// InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(System.out);
// InputReader in = new InputReader(new
// File("ethan_traverses_a_tree.txt"));
// PrintWriter out = new PrintWriter(new
// File("ethan_traverses_a_tree-output.txt"))
int n = in.nextInt();
g = new ArrayList<List<Integer>>();
tree = new ArrayList<List<Integer>>();
for (int i = 0; i < n; i++) {
g.add(new ArrayList<Integer>());
tree.add(new ArrayList<Integer>());
}
dpSpe = new Node[n];
dpNotSpe = new Node[n];
numEdges = new int[n];
weight = new int[n];
for (int i = 0; i < n - 1; i++) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
g.get(u).add(v);
g.get(v).add(u);
}
if (n == 2) {
out.printf("2 2\n");
out.printf("1 1\n");
} else {
for (int i = 0; i < n; i++) {
numEdges[i] = g.get(i).size();
}
toRootedTree(0, -1);
dpAns(0);
Node ans;
if (dpSpe[0].greater(dpNotSpe[0])) {
ans = dpSpe[0];
dpPath(0, true);
} else {
ans = dpNotSpe[0];
dpPath(0, false);
}
out.printf("%d %d\n", ans.maxnum, ans.minsum);
for (int i = 0; i < n; i++) {
if (i == n - 1) {
out.printf("%d\n", weight[i]);
} else {
out.printf("%d ", weight[i]);
}
}
}
out.close();
}
public static void dpPath(int now, boolean spe) {
if (spe) {
weight[now] = numEdges[now];
for (Integer v : tree.get(now)) {
dpPath(v, false);
}
} else {
weight[now] = 1;
for (Integer v : tree.get(now)) {
if (dpNotSpe[v].greater(dpSpe[v])) {
dpPath(v, false);
} else {
dpPath(v, true);
}
}
}
}
public static void dpAns(int now) {
for (Integer v : tree.get(now)) {
dpAns(v);
}
Node spe = new Node(1, numEdges[now]);
for (Integer v : tree.get(now)) {
spe.maxnum = spe.maxnum + dpNotSpe[v].maxnum;
spe.minsum = spe.minsum + dpNotSpe[v].minsum;
}
dpSpe[now] = spe;
Node notSpe = new Node(0, 1);
for (Integer v : tree.get(now)) {
Node node;
if (dpSpe[v].greater(dpNotSpe[v])) {
node = dpSpe[v];
} else {
node = dpNotSpe[v];
}
notSpe.maxnum = notSpe.maxnum + node.maxnum;
notSpe.minsum = notSpe.minsum + node.minsum;
}
dpNotSpe[now] = notSpe;
}
public static void toRootedTree(int now, int parent) {
for (Integer v : g.get(now)) {
if (v != parent) {
tree.get(now).add(v);
toRootedTree(v, now);
}
}
}
static class Node {
int maxnum;
int minsum;
public Node(int maxnum, int minsum) {
this.maxnum = maxnum;
this.minsum = minsum;
}
public boolean greater(Node node) {
if (maxnum > node.maxnum || (maxnum == node.maxnum && minsum < node.minsum)) {
return true;
}
return false;
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public InputReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public boolean hasNext() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["4\n1 2\n2 3\n2 4", "3\n1 2\n1 3", "2\n1 2", "9\n3 4\n7 6\n2 1\n8 3\n5 6\n1 8\n8 6\n9 6"] | 2 seconds | ["3 4\n1 1 1 1", "2 3\n1 1 1", "2 2\n1 1", "6 11\n1 1 1 1 1 1 1 3 1"] | NoteThis is the tree for the first test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$1$$$, $$$3$$$ and $$$4$$$. It impossible to assign weights so that all vertices are good vertices. The minimum sum of weights in this case is $$$1+1+1+1=4$$$, and it is impossible to have a lower sum because the weights have to be positive integers.This is the tree for the second test case: In this case, if you assign a weight of $$$1$$$ to each vertex, then the good vertices (which are painted black) are $$$2$$$ and $$$3$$$. It can be proven that this is an optimal assignment. | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"dp",
"implementation",
"trees"
] | dc3848faf577c5a49273020a14b343e1 | The first line contains one integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$) — the number of vertices in the tree. Then, $$$n−1$$$ lines follow. Each of them contains two integers $$$u$$$ and $$$v$$$ ($$$1\le u,v\le n$$$) denoting an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. | 2,000 | In the first line print two integers — the maximum number of good vertices and the minimum possible sum of weights for that maximum. In the second line print $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$1\le w_i\le 10^9$$$) — the corresponding weight assigned to each vertex. It can be proven that there exists an optimal solution satisfying these constraints. If there are multiple optimal solutions, you may print any. | standard output |
Subsets and Splits