import java.util.Scanner;

/**
 *
 * @author cs18097
 */
public class Main {
    //abc141 d

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int num = sc.nextInt();
        int ary[] = new int[n];
        for(int i = 0;i < ary.length;i++) ary[i] = sc.nextInt();
        while(num > 0){
            int k = 0;
            int max = -1;
            for(int j = 0;j <ary.length;j++){
                if(max<ary[j])k = j;
            }
            ary[k] /=2;
            num--;
        }
        long ans=0;
        for(int i = 0; i<ary.length;i++)ans += ary[i];
        System.out.print(ans);
    }
}


import java.io.*;
import java.util.*;

@SuppressWarnings("unused")
class Main {

    // Generated by 1.1.5 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
    public static void main(String[] args) throws Exception {
        final Scanner sc = new Scanner(System.in);
        long N;
        N = sc.nextLong();
        long M;
        M = sc.nextLong();

        PriorityQueue<Integer> A = new PriorityQueue<>(Comparator.reverseOrder());
        for(int i = 0 ; i < N ; i++){
            A.add(sc.nextInt());
        }
        solve(N, M, A);
    }

    static void solve(long N, long M, PriorityQueue<Integer> A){
        for (int i = 0; i < M; i++) {
            int max = A.poll();
            A.offer(max/2);
        }
        long ans = 0;
        for (int i : A) {
            ans += i;
        }
        System.out.println(ans);
    }
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 400 points

Problem Statement

Takahashi is going to buy N items one by one.

The price of the i-th item he buys is A_i yen (the currency of Japan).

He has M discount tickets, and he can use any number of them when buying an item.

If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded down to the nearest integer) yen.

What is the minimum amount of money required to buy all the items?

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the minimum amount of money required to buy all the items.

Sample Input 1

3 3
2 13 8

Sample Output 1

9

We can buy all the items for 9 yen, as follows:

Buy the 1-st item for 2 yen without tickets.

Buy the 2-nd item for 3 yen with 2 tickets.

Buy the 3-rd item for 4 yen with 1 ticket.

Sample Input 2

4 4
1 9 3 5

Sample Output 2

6

Sample Input 3

1 100000
1000000000

Sample Output 3

0

We can buy the item priced 1000000000 yen for 0 yen with 100000 tickets.

Sample Input 4

10 1
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 4

9500000000

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

class Main {
    static Scanner sc = new Scanner();

    public static void main(final String[] args) throws IOException {
        int n = sc.nextInt();
        int m = sc.nextInt();
        PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder());

        for (int i = 0; i < n; i++) {
            pq.add(sc.nextInt());
        }
        for (int i = 0; i < m; i++) {
            int first = (int) pq.poll();
            first = first/2;
            pq.add(first);
        }
        int ans = 0;
        for (int i = 0; i < n; i++) {
          ans += (int)pq.poll();
        }
        System.out.println(ans);
    }

    static class Scanner {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 1 << 15);
        StringTokenizer tokenizer;
        String next() throws IOException {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                tokenizer = new StringTokenizer(reader.readLine());
            }
            return tokenizer.nextToken();
        }
        int nextInt() throws IOException {
            return Integer.parseInt(next());
        }
        long nextLong() throws IOException {
            return Long.parseLong(next());
        }
    }
}


import java.util.*;
public class Main {
	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int M = sc.nextInt();
		int A[] = new int[N];
		PriorityQueue<Double> pq = new PriorityQueue<Double>(Collections.reverseOrder());;
		for(int i = 0; i < N; i++) {
			A[i] = sc.nextInt();
			pq.add((double)A[i]);
		}

		for(int i = 0; i < M; i++) {
			double temp = pq.poll();
			temp = temp / 2;
			pq.add(temp);
		}

		long ans = 0;
		for(int i = 0; i < N; i++) {
			ans += Math.floor(pq.poll());
		}
		System.out.println(ans);
	}
}


import java.util.*;

public class Main {

	public static void main (String[] args)  {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		PriorityQueue<Integer> queue = new PriorityQueue<Integer>(new Comparator<Integer>() {
		public int compare(Integer i1, Integer i2) {
			return i2.intValue() - i1.intValue();
		}
		});
		for (int i = 0; i < n; i++) {
			queue.add(sc.nextInt());
		}
		for (int i = 0; i < m; i++) {
			int x = queue.poll();
			queue.add(x / 2);
		}
		long total = 0;
		while (queue.size() > 0) {
			total += queue.poll();
		}
		System.out.println(total);
	}
}


import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        int m = sc.nextInt();

        int[] a = new int[n];

//        for (int i=0; i<n; i++) a[i] = sc.nextInt();

        PriorityQueue<Double> pq = new PriorityQueue<>();

        for (int i=0; i<n; i++){
            pq.add(sc.nextDouble()*(-1));
        }

        for (int i=0; i<m; i++){
            double p = pq.poll()/2;
            pq.add(p);
        }

        long ans =0;
        while (!pq.isEmpty()){
            ans += pq.poll()*(-1);
        }

        System.out.println(ans);

    }
}


import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;

public class Main {
    public static void debug(String str) {
        System.out.println(str);
    }

    public static void main(String[] args) {

        int N;
        int M;
        long[] Ai;

        Comparator<Double> comp = Comparator.comparingDouble(d->d.doubleValue());
        PriorityQueue<Double> pq = new PriorityQueue<>(comp.reversed());

        try (Scanner sc = new Scanner(System.in)) {
            N = sc.nextInt();
            M = sc.nextInt();

            Ai = new long[N];
            for (int i = 0; i < Ai.length; i++) {
                Ai[i] = sc.nextLong();
            }
        }
        for(long l : Ai){
            pq.add((double) l);
        }
        Double d ;
        while(M >0){
            d = pq.poll();
            double temp = d/2;
            pq.add(temp);
            M--;
        }
        long result = 0;
        while((d = pq.poll()) != null){
            result += Math.floor(d);
        }
        System.out.println(result);
    }
}


import java.io.*;
import java.util.*;

public class Main {
	static void solve() {
		int n = ni();
		char s[] = ns(n);
		int dp[][] = new int[n+1][n+1];
		for(int i=n-1;i>=0;i--) {
			for(int j=n-1;j>=0;j--) {
				if(s[i] == s[j]) {
					dp[i][j] = dp[i+1][j+1] + 1;
				}
			}
		}
		long ans = 0;
		for(int i=0;i<n-1;i++) {
			for(int j=i+1;j<n;j++) {
				long t = min(dp[i][j], j-i);
				ans = max(ans, t);
			}
		}
		out.println(ans);
	}

	//constant
	static final long mod = (long) 1e9 + 7;
	static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
	static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };
	static final int inf = Integer.MAX_VALUE / 2;
	static final long linf = Long.MAX_VALUE / 3;
	static final double dinf = Double.MAX_VALUE / 3;
	static final double eps = 1e-10;
	static final double pi = Math.PI;
	static StringBuilder sb = new StringBuilder();
	static InputStream is;
	static PrintWriter out;
	static String INPUT = "";

	//libraries
	static void reverse(int ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			int t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void reverse(long ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			long t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void reverse(double ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			double t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void reverse(char ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			char t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static String getReverse(String s) {
		char c[] = s.toCharArray();
		reverse(c);
		s = String.valueOf(c);
		return s;
	}

	static <T> void reverse(List<T> ls) {
		int sz = ls.size();
		for (int i = 0; i < sz / 2; i++) {
			T t = ls.get(i);
			ls.set(i, ls.get(sz - 1 - i));
			ls.set(sz - 1 - i, t);
		}
	}

	static <T> void reverse(T[] ar) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			T t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void sbnl() {//StringBuilderに改行文字をappendする
		sb.append("\n");
	}

	static int lowerBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int lowerBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int lowerBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int lowerBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static <T> int lowerBound(List<T> ls, T x) throws RuntimeException {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) >= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) >= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) >= 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static <T> int upperBound(List<T> ls, T x) throws RuntimeException {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) > 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) > 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) > 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static <T> int rupperBound(List<T> ls, T x) throws RuntimeException {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) < 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) < 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) < 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static <T> int rlowerBound(List<T> ls, T x) {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) <= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) <= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) <= 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static int[] concat(int x, int arr[]) {
		int ret[] = new int[arr.length + 1];
		System.arraycopy(arr, 0, ret, 1, ret.length - 1);
		ret[0] = x;
		return ret;
	}

	static int[] concat(int arr[], int x) {
		int ret[] = new int[arr.length + 1];
		System.arraycopy(arr, 0, ret, 0, ret.length - 1);
		ret[ret.length - 1] = x;
		return ret;
	}

	static long[] concat(long x, long arr[]) {
		long ret[] = new long[arr.length + 1];
		System.arraycopy(arr, 0, ret, 1, ret.length - 1);
		ret[0] = x;
		return ret;
	}

	static long[] concat(long arr[], long x) {
		long ret[] = new long[arr.length + 1];
		System.arraycopy(arr, 0, ret, 0, ret.length - 1);
		ret[ret.length - 1] = x;
		return ret;
	}

	static int max(int x, int y) {
		return Math.max(x, y);
	}

	static int min(int x, int y) {
		return Math.min(x, y);
	}

	static int max(int x, int y, int z) {
		x = Math.max(x, y);
		x = Math.max(x, z);
		return x;
	}

	static int min(int x, int y, int z) {
		x = Math.min(x, y);
		x = Math.min(x, z);
		return x;
	}

	static long max(long x, long y) {
		return Math.max(x, y);
	}

	static long min(long x, long y) {
		return Math.min(x, y);
	}

	static long max(long x, long y, long z) {
		x = Math.max(x, y);
		x = Math.max(x, z);
		return x;
	}

	static long min(long x, long y, long z) {
		x = Math.min(x, y);
		x = Math.min(x, z);
		return x;
	}

	static double max(double x, double y) {
		return Math.max(x, y);
	}

	static double min(double x, double y) {
		return Math.min(x, y);
	}

	static double max(double x, double y, double z) {
		x = Math.max(x, y);
		x = Math.max(x, z);
		return x;
	}

	static double min(double x, double y, double z) {
		x = Math.min(x, y);
		x = Math.min(x, z);
		return x;
	}

	static void sort(int[] ar) {
		Arrays.sort(ar);
	}

	static void sort(long[] ar) {
		Arrays.sort(ar);
	}

	static void sort(double[] ar) {
		Arrays.sort(ar);
	}

	static void sort(char[] ar) {
		Arrays.sort(ar);
	}

	static void rsort(int[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			int tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void rsort(long[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			long tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void rsort(double[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			double tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void rsort(char[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			char tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void fill(int arr[], int x) {
		Arrays.fill(arr, x);
	}

	static void fill(long arr[], long x) {
		Arrays.fill(arr, x);
	}

	static void fill(boolean arr[], boolean x) {
		Arrays.fill(arr, x);
	}

	static void fill(double arr[], double x) {
		Arrays.fill(arr, x);
	}

	static void fill(int arr[][], int x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	static void fill(long arr[][], long x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	static void fill(double arr[][], double x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	static void fill(boolean arr[][], boolean x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	//MOD culc
	static long plus(long x, long y) {
		long res = (x + y) % mod;
		return res < 0 ? res + mod : res;
	}

	static long sub(long x, long y) {
		long res = (x - y) % mod;
		return res < 0 ? res + mod : res;
	}

	static long mul(long x, long y) {
		long res = (x * y) % mod;
		return res < 0 ? res + mod : res;
	}

	static long div(long x, long y) {
		long res = x * pow(y, mod - 2) % mod;
		return res < 0 ? res + mod : res;
	}

	static long pow(long x, long y) {
		if (y < 0)
			return 0;
		if (y == 0)
			return 1;
		if (y % 2 == 1)
			return (x * pow(x, y - 1)) % mod;
		long root = pow(x, y / 2);
		return root * root % mod;
	}

	public static void main(String[] args) throws Exception {
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);
		solve();
		out.flush();
	}

	//input
	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 int skip() {
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

	@SuppressWarnings("unused")
	private static double nd() {
		return Double.parseDouble(ns());
	}

	@SuppressWarnings("unused")
	private static char nc() {
		return (char) skip();
	}

	private static String ns() {
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b))) {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private static char[] ns(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);
	}

	@SuppressWarnings("unused")
	private static char[][] nm(int n, int m) {
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	@SuppressWarnings("unused")
	private static int[] na(int n) {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	@SuppressWarnings("unused")
	private static long[] nla(int n) {
		long[] a = new long[n];
		for (int i = 0; i < n; i++)
			a[i] = nl();
		return a;
	}

	private static int ni() {
		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();
		}
	}

	@SuppressWarnings("unused")
	private static long nl() {
		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();
		}
	}

}

Score : 500 points

Problem Statement

Given is a string S of length N.

Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.

More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:

l_1 + len \leq l_2

S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)

If there is no such integer len, print 0.

Constraints

2 \leq N \leq 5 \times 10^3

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.

Sample Input 1

5
ababa

Sample Output 1

2

The strings satisfying the conditions are: a, b, ab, and ba. The maximum length among them is 2, which is the answer.
Note that aba occurs twice in S as contiguous substrings, but there is no pair of integers l_1 and l_2 mentioned in the statement such that l_1 + len \leq l_2.

Sample Input 2

2
xy

Sample Output 2

0

No non-empty string satisfies the conditions.

Sample Input 3

13
strangeorange

Sample Output 3

5


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Map;

public class Main {
    InputStream is;

    int __t__ = 1;
    int __f__ = 0;
    int __FILE_DEBUG_FLAG__ = __f__;
    String __DEBUG_FILE_NAME__ = "src/A3";

    FastScanner in;
    PrintWriter out;

    public void solve() {
        int n = in.nextInt();
        String s = in.next();
        long[][] dp = new long[n+1][n+1];
        for (int d = 1; d <= n; d++) {
            for (int i = 0; i < n - d; i++) {
                int j = i + d;
                if (s.charAt(i) == s.charAt(j)) {
                    dp[i+1][j+1] = dp[i][j] + 1;
                }
            }
        }
        long res = 0;
        for (int i = 0; i <= n; i++) {
            for (int j = i + 1; j <= n; j++) {
                res = Math.max(res, Math.min(dp[i][j], j - i));
            }
        }
        System.out.println(res);
    }

    /* MOD_CALCULATION */
    static long MOD = 1000000007L;
    static long ADD(long a, long b) {
        return (a + b) % MOD;
    }

    static long SUB(long a, long b) {
        return (a - b + MOD) % MOD;
    }

    static long MULT(long a, long b) {
        return (a * b) % MOD;
    }

    static long POW(long a, long x) {
        long res = 1;
        for ( ; x > 0; x >>= 1) {
            if (x % 2 == 1) res = MULT(res, a);
            a = MULT(a, a);
        }

        return res;
    }

    static long DIV(long a, long b) {
        return MULT(a, POW(b, MOD - 2));
    }
    /* end */

    public void run() {
        if (__FILE_DEBUG_FLAG__ == __t__) {
            try {
                is = new FileInputStream(__DEBUG_FILE_NAME__);
            } catch (FileNotFoundException e) {
                // TODO 自動生成された catch ブロック
                e.printStackTrace();
            }
            System.out.println("FILE_INPUT!");
        } else {
            is = System.in;
        }
        in = new FastScanner(is);
        out = new PrintWriter(System.out);

        solve();
    }

    public static void main(final String[] args) {
        new Main().run();
    }

    class FastScanner {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public FastScanner(InputStream stream) {
            this.stream = stream;
            // stream = new FileInputStream(new File("dec.in"));

        }

        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++];
        }

        boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        boolean isEndline(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        int[] nextIntArray(int n) {
            int[] array = new int[n];
            for (int i = 0; i < n; i++)
                array[i] = nextInt();

            return array;
        }

        int[][] nextIntMap(int n, int m) {
            int[][] map = new int[n][m];
            for (int i = 0; i < n; i++) {
                map[i] = in.nextIntArray(m);
            }
            return map;
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        long[] nextLongArray(int n) {
            long[] array = new long[n];
            for (int i = 0; i < n; i++)
                array[i] = nextLong();

            return array;
        }

        long[][] nextLongMap(int n, int m) {
            long[][] map = new long[n][m];
            for (int i = 0; i < n; i++) {
                map[i] = in.nextLongArray(m);
            }
            return map;
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        double[] nextDoubleArray(int n) {
            double[] array = new double[n];
            for (int i = 0; i < n; i++)
                array[i] = nextDouble();

            return array;
        }

        double[][] nextDoubleMap(int n, int m) {
            double[][] map = new double[n][m];
            for (int i = 0; i < n; i++) {
                map[i] = in.nextDoubleArray(m);
            }
            return map;
        }

        String next() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        String[] nextStringArray(int n) {
            String[] array = new String[n];
            for (int i = 0; i < n; i++)
                array[i] = next();

            return array;
        }

        String nextLine() {
            int c = read();
            while (isEndline(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isEndline(c));
            return res.toString();
        }
    }
}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		String s = sc.next();
		int[][] dp = new int[n][n];

		for(int j = n-1; j>=0; j--) {
			int i = n-1;
			if(s.charAt(i) == s.charAt(j)) dp[i][j] = 1;
			else dp[i][j] = 0;
		}

		for(int i=n-1; i>=0; i--) {
			int j = n-1;
			if(s.charAt(i) == s.charAt(j)) dp[i][j] = 1;
			else dp[i][j] = 0;
		}

		for(int i = n-2; i>=0; i--) {
			for(int j = n-2; j>=0; j--) {
				if(s.charAt(i) == s.charAt(j)) dp[i][j] = dp[i+1][j+1]+1;
				else dp[i][j] = 0;
			}
		}

		int len = 0;
		for(int i=0; i<n; i++) {
			for(int j = 0; j<n; j++) {
				if(i+dp[i][j] <= j) len = Math.max(len, dp[i][j]);
			}
		}
		System.out.println(len);
	}
}


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
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.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;

class Main {

    private static PrintWriter out;

    private static void mprintln(Object... ar) {
        for (Object i : ar) {
            out.print(i + " ");
        }
        out.println();
    }

    public static void main(String[] args) throws FileNotFoundException {

        // Input from file
        // File inputFile = new File("JavaFile.txt");
        // File outputFile = new File("JavaOutputFile.txt");
        // FileReader fileReader = new FileReader(inputFile);
        // Here it ends

        MyScanner sc = new MyScanner();
        // MyScanner sc = new MyScanner(fileReader);

        out = new PrintWriter(new BufferedOutputStream(System.out)); // Output to console
        // out = new PrintWriter(new PrintStream(outputFile)); // Output to file

        getAns(sc);

        out.close();
    }

    /*
     *Don't use builtin function (Math.ceil)
     */

    static final long MOD = (long) (1e9 + 7);

    private static void getAns(MyScanner sc) {
        int n = sc.ni();
        String s = sc.nn();

        int start = 0, end = n / 2 + 1;

        outer:
        while (start < end) {
            int mid = start + end + 1 >> 1;
//            System.out.println(mid);
            HashSet<Integer> set = new HashSet<>();
            for (int i = 0, size = s.length(); i <= size - mid; i++) {

                set.add(s.substring(i, i + mid)
                         .hashCode());

                if (i + 2 * mid <= size && set.contains(s.substring(i + mid, i + 2 * mid)
                                  .hashCode())) {
                    start = mid;
                    continue outer;
                }
            }

            end = mid - 1;
        }

        out.println(start);
    }

    static class MyScanner {

        BufferedReader br;
        StringTokenizer st;

        MyScanner(FileReader fileReader) {
            br = new BufferedReader(fileReader);
        }

        MyScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String nn() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        String nextLine() {
            String ans = "";
            try {
                ans = br.readLine();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return ans;
        }

        char nc() {
            return nn().charAt(0);
        }

        int ni() {
            return Integer.parseInt(nn());
        }

        long nl() {
            return Long.parseLong(nn());
        }

        double nd() {
            return Double.parseDouble(nn());
        }

        int[] niArr0(int n) {
            int[] ar = new int[n];
            for (int i = 0; i < n; i++) {
                ar[i] = ni();
            }
            return ar;
        }

        int[] niArr1(int n) {
            int[] ar = new int[n + 1];
            for (int i = 1; i <= n; i++) {
                ar[i] = ni();
            }
            return ar;
        }

        Long[] nlArr0(int n) {
            Long[] ar = new Long[n];
            for (int i = 0; i < n; i++) {
                ar[i] = nl();
            }
            return ar;
        }

        Long[] nlArr1(int n) {
            Long[] ar = new Long[n + 1];
            for (int i = 1; i <= n; i++) {
                ar[i] = nl();
            }
            return ar;
        }
    }
}


import java.util.Scanner;

public class Main {
    public static void debug(String str) {
        System.out.println(str);
    }

    public static void main(String[] args) {

        int N;
        String S;

        try (Scanner sc = new Scanner(System.in)) {
            N = sc.nextInt();
            S = sc.next();

        }
        //len(暫定値)
        int NStart = 0;
        int NEnd = N;
        int window =0;
        int result = 0;
        while (true) {

            window = (NEnd + NStart) / 2;

            //探索
            boolean check = chackSub(S, window);
            if (check) {
                result = window;
                NStart = window;
            } else {
                NEnd = window;
            }
            if(NEnd - NStart  <=1){
                break;
            }
        }

        System.out.println(result);
    }

    private static boolean chackSub(String S, int window) {
        int i = 0;
        while (true) {
            int start = i;
            int end = start + window;

            if (end + window > S.length()) {
                break;
            }
            String sub1 = S.substring(start, end);
            String sub2 = S.substring(end+1);

            if (sub2.contains(sub1)) {
                return true;
            }
            i++;
        }
        return false;
    }
}


import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        String s = sc.next();

        int answer = 0;
        for(int i = 0; i< n; i++ ) {
            for (int j = i + 1; j <= n; j++) {
                String base = s.substring(i, j);
                String replace = s.replaceAll(base, "★");

                long count = replace.chars().filter(ch -> ch == '★').count();
                if (count > 1) {
                    if (answer < base.length()) {
                        answer = base.length();
                    }
                }
            }
        }

        System.out.println(answer);

    }
}


import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws Exception {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int a = Integer.parseInt(br.readLine());
        String s = br.readLine();

        if ( a < 3200 ) {
            System.out.println("red");
        } else {
            System.out.println(s);
        }

    }
}

Score : 100 points

Problem Statement

You will be given an integer a and a string s consisting of lowercase English letters as input.

Write a program that prints s if a is not less than 3200 and prints red if a is less than 3200.

Constraints

2800 \leq a < 5000

s is a string of length between 1 and 10 (inclusive).

Each character of s is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

a
s

Output

If a is not less than 3200, print s; if a is less than 3200, print red.

Sample Input 1

3200
pink

Sample Output 1

pink

a = 3200 is not less than 3200, so we print s = pink.

Sample Input 2

3199
pink

Sample Output 2

red

a = 3199 is less than 3200, so we print red.

Sample Input 3

4049
red

Sample Output 3

red

a = 4049 is not less than 3200, so we print s = red.


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        {
            Scanner input = new Scanner(System.in);
            int a = input.nextInt();
            String s = input.next();
            if(a < 3200)
                System.out.println("red");

            else
                System.out.println(s);
        }
    }
}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);
		int n = scn.nextInt();
		String m = scn.next();
		System.out.println(n>=3200?m:"red");
		scn.close();
	}
}


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    int a = scanner.nextInt();
    String s = scanner.next();
    if (a >= 3200) System.out.println(s);
    else {
      System.out.println("red");
    }
  }
}


import java.util.Scanner;

public class Main {

	static int n;
	static int q;
	static int[] result ;
	static int[][] inheritence;

	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		// 整数の入力
		n = sc.nextInt();
		q = sc.nextInt();

		result = new int[n];
		inheritence = new int[n-1][2];

		for(int i=0; i<n-1; i++) {
			result[i] =  0;
			inheritence[i][0] =  sc.nextInt();
			inheritence[i][1] =  sc.nextInt();
		}

		for(int i=0; i<q; i++) {
			int p =  sc.nextInt();
			int x =  sc.nextInt();

			for(int k=n-1; k>=0; k--) {
				if(isIncluded(k+1, p)) {
					result[k] += x;
				}
				if(k<p) {
					break;
				}
			}
		}

		for(int i=0; i<n; i++) {
			if(i != 0) {
				System.out.print(" ");
			}
			System.out.print(result[i]);
		}

	}

	private static boolean isIncluded(int target, int source) {
		int parent = 0;
		for(int i=0; i<n-1; i++) {
			if(target == source) {
				return true;
			}
			if(inheritence[i][1] == target) {
				parent = inheritence[i][0];
				if(parent == source) {
					return true;
				}
				target = inheritence[i][0];
				i = -1;
				continue;
			}
		}
		return false;
	}
}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		if (sc.nextInt() >= 3200) {
			System.out.println(sc.nextLine());
		} else {
			System.out.println("red");
		}
	}
}


import java.util.*;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		// 整数の入力
		int a = sc.nextInt();
		// スペース区切りの整数の入力
		String s = sc.next();
      	if(a >= 3200){
          System.out.println(s);
        }
        else
        {
          System.out.println("red");
        }

	}
}


import java.util.*;
import java.io.*;

public class Main{
  public static void main(String args[]) throws IOException
  {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int a = Integer.parseInt(br.readLine());
    String string = br.readLine();

    if(a>=3200)
    {
      System.out.println(string);
    }
    else
    {
      System.out.println("red");
    }
  }
}


import java.util.*;

public class Main {
    public static void main (String[]args){

        Scanner scanner = new Scanner(System.in);

        int a = scanner.nextInt();
        String s = scanner.nextLine();

        if (a < 3200){
          System.out.println("red");
        } else{
          System.out.println(s);
        }

        scanner.close();

    }
}


import java.util.*;

class Main{
  public static void main(String args[]){
    Scanner sc = new Scanner(System.in);
    int a = sc.nextInt();
    if(a<3200){
      System.out.println("red");
    }else{
      System.out.println(sc.next());
    }
  }
}


import java.util.*;
import static java.lang.Math.*;

public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);

		// 入力
		int a = sc.nextInt();
		String s = sc.next();

		// 出力
		if(a >= 3200){
		  System.out.println(s);
		}else{
		    System.out.println("red");
		}
	}

}


import java.util.*;
public class Main {

	public static void main(String[] args) {
		Scanner stdIn = new Scanner(System.in);
		int a = stdIn.nextInt();
		String s = stdIn.next();
		if(a >= 3200) System.out.println(s);
		else System.out.println("red");

	}

}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;

/** テンプレート */
public class Main {
	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int a = sc.nextInt();
		String s = sc.next();

		//************************************/
		// ここから出力処理
		//************************************/
		PrintWriter out = new PrintWriter(System.out);
		if(a >= 3200) {
			out.println(s);

		}else {
			out.println("red");

		}
		// 最後に必ずFlush
		out.flush();
	}
}

//public class Main {
//	final static int SSSSS = 1000000;
//
//
//	public static void main(String[] args) {
//		FastScanner sc = new FastScanner();
//		int N = sc.nextInt();
//		int K = sc.nextInt();
//
//		double ans = 0;
//		int min = Main.calc(K);
//		int count = 1;
//
//
//		if(K <= N) {
//
//			for(int i=2; i<=K-1; i++) {
//
//				 count += min / Main.calc((int)Math.ceil((double)K / i));
//
//			}
////			//deb
////			out.println(count);
//
//			ans = (double)(count+(N-K+1)*min)/(N * min);
//
//		}else {
//			for(int i=2; i<=N; i++) {
////				//deb
////				out.println("count:");
////				out.println(count);
////				out.println("ceil:");
////				out.println(((int)Math.ceil(K / i)));
////				out.println("calc:");
////				out.println(Main.calc((int)Math.ceil(K / i)));
////				out.println("min / calc:");
////				out.println(min / Main.calc((int)Math.ceil(K / i)));
////				out.flush();
////				//
//
//
//				 count += min / Main.calc((int)Math.ceil((double)K / i));
//			}
//
//			ans = (double)count/(N * min);
//		}
//
//
//
//		//************************************/
//		// ここから出力処理
//		//************************************/
//		PrintWriter out = new PrintWriter(System.out);
//
//		out.println(ans);
//
//		// 最後に必ずFlush
//		out.flush();
//	}
//
//
//	/**
//	 * xが2のべき乗かどうか調べる関数
//	 * @param x
//	 * @return 2のべき乗ならtrue。0はfalse。
//	 */
//	static boolean isPowerOfTwo(int x){
//	    return x > 0 && (x & (x - 1)) == 0;
//	}
//
//	static int calc(int num) {
//	    if(isPowerOfTwo(num)){
//	    	return num;
//	    }
//
//		int ret = 0;
//		for(int shift=2; shift<31; shift++){ // 32bit符号付整数なので30回シフト=2^31が限界
//			ret = 1 << shift;                // 1を左シフトして2のべき乗を生成
//			if(ret > num){
//				return  ret;
//			}
//		}
//		return ret;
//	}
//
//
//}

///** ★★テンプレート */
//public class Main {
//	public static void main(String[] args) {
//		FastScanner sc = new FastScanner();
//		int N = sc.nextInt();
//		int M = sc.nextInt();
//
//		int[] ary = new int[N];
//		for (int i = 0; i < N; i++) {
//			ary[i] = sc.nextInt();
//		}
////
////		Pair[] a = { new Pair(0, 5), new Pair(1, 10), new Pair(2, 3) };
////		Arrays.sort(a, new Comparator<Pair>() {
////			public int compare(Pair o1, Pair o2) {
////				return Integer.compare(o1.v, o2.v); //Java7以降
////			}
////		});
//
//		//************************************/
//		// ここから出力処理
//		//************************************/
//		PrintWriter out = new PrintWriter(System.out);
//
//		out.println("hoge");
//
//		// 最後に必ずFlush
//		out.flush();
//	}
//}

/** スキャン用 */
class FastScanner {
	private final InputStream in = System.in;
	private final byte[] buffer = new byte[1024];
	private int ptr = 0;
	private int buflen = 0;

	/** クラス内部用だよ */
	private boolean hasNextByte() {
		if (ptr < buflen) {
			return true;
		} else {
			ptr = 0;
			try {
				buflen = in.read(buffer);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (buflen <= 0) {
				return false;
			}
		}
		return true;
	}

	/** クラス内部用だよ */
	private int readByte() {
		if (hasNextByte()) {
			return buffer[ptr++];
		} else {
			return -1;
		}
	}

	/**
	 * クラス内部用だよ
	 * ASCII の文字の内、表示用の文字を返す関数
	 *
	 * @return 改行とか制御文字じゃない、表示用文字ならtrue
	 * */
	private static boolean isPrintableChar(int c) {
		return 33 <= c && c <= 126;
	}

	/**
	 * @return 改行文字とか空白以外を除いた、次の文字があればtrue
	 * */
	public boolean hasNext() {
		while (hasNextByte() && !isPrintableChar(buffer[ptr])) {
			ptr++;
		}
		return hasNextByte();
	}

	/**
	 *
	 * @return 次の文字列
	 */
	public String next() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}

		StringBuilder sb = new StringBuilder();
		int b = readByte();
		while (isPrintableChar(b)) {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	/**
	 *
	 * @return 次のLong
	 */
	public long nextLong() {
		if (!hasNext())
			throw new NoSuchElementException();
		long n = 0;
		boolean minus = false;
		int b = readByte();
		if (b == '-') {
			minus = true;
			b = readByte();
		}
		if (b < '0' || '9' < b) {
			throw new NumberFormatException();
		}
		while (true) {
			if ('0' <= b && b <= '9') {
				n *= 10;
				n += b - '0';
			} else if (b == -1 || !isPrintableChar(b)) {
				return minus ? -n : n;
			} else {
				throw new NumberFormatException();
			}
			b = readByte();
		}
	}

	/**
	 *
	 * @return 次のInt
	 */
	public int nextInt() {
		long nl = nextLong();
		if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
			throw new NumberFormatException();
		return (int) nl;
	}

	/**
	 *
	 * @return 次のDouble
	 */
	public double nextDouble() {
		return Double.parseDouble(next());
	}
}

class PairII {
	int k;
	int v;

	public PairII(int k, int v) {
		this.k = k;
		this.v = v;
	}
}

class PairSI {
	String k;
	int v;
	int num; // 出現順

	public PairSI(String k, int v, int num) {
		this.k = k;
		this.v = v;
		this.num = num;
	}
}

//class Pair<K, V> extends AbstractMap.SimpleEntry<K, V> {
//	/** serialVersionUID. */
//	private static final long serialVersionUID = 6411527075103472113L;
//
//	public Pair(final K key, final V value) {
//		super(key, value);
//	}
//}


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // Your code here!
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();

        List<Integer>[] to = new List[n];
        for (int i = 0; i < n; i++) {
            to[i] = new ArrayList<Integer>();
        }

        // リストの作成
        for (int i = 0; i < n - 1; i++) {
            int s = sc.nextInt() - 1;
            int t = sc.nextInt() - 1;
            to[s].add(t);
            to[t].add(s);
        }

        int[] first = new int[n];
        for (int i = 0; i < k; i++) {
            int p = sc.nextInt() - 1;
            int count = sc.nextInt();
            first[p] += count;
        }

        int[] last = new int[n];

        // visited[i][j]: 当該マスを既に通ったか否か
        boolean[] visited = new boolean[n];
        visited[0] = true;

        // steps = BFS((0, 0)→(h, w)までの最短経路の深さ)
        Queue<int[]> que = new ArrayDeque<int[]>();
        que.add(new int[]{0, 0});
        while (!que.isEmpty()) {
            int[] cur = que.poll();
            int p = cur[0];
            int count = cur[1] + first[p];
            last[p] = count;

            for (Integer q : to[p]) {
                if (!visited[q]) {
                    que.add(new int[]{q, count});
                    visited[q] = true;
                }
            }
        }

        for (int i = 0; i < n; i++) {
            System.out.print(last[i]);
            if (i != n - 1) {
                System.out.print(" ");
            } else {
                System.out.println();
            }
        }
    }
}

Score : 400 points

Problem Statement

Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.

Now, the following Q operations will be performed:

Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.

Find the value of the counter on each vertex after all operations.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq Q \leq 2 \times 10^5

1 \leq a_i < b_i \leq N

1 \leq p_j \leq N

1 \leq x_j \leq 10^4

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

Output

Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.

Sample Input 1

4 3
1 2
2 3
2 4
2 10
1 100
3 1

Sample Output 1

100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:

Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.

Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.

Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.

Sample Input 2

6 2
1 2
1 3
2 4
3 6
2 5
1 10
1 10

Sample Output 2

20 20 20 20 20 20


import java.util.Scanner;

public class Main {
	static Scanner scan = new Scanner(System.in);
	static int N = scan.nextInt();
	static int Q = scan.nextInt();
	static int[]a = new int[N];
	static int[]b = new int[N];
	static int[]p = new int[N+1];
	static int[]x = new int[N+1];
	static int counter = 0;
	static int[] tyoutencount = new int[N+1];
	static int[] tyoutenXcount = new int[N+1];
	static boolean[] tyoutenserch = new boolean[N+1];
	static int[][]edge = new int[N+1][N+1];//余分に作っておく

	public static void main(String[]args) {
		for(int i = 1;i<N;i++) {//ちょっと工夫1~N-1個
			a[i] = scan.nextInt();
			b[i] = scan.nextInt();
			edge[a[i]][b[i]] = 1;//N-1こ分の変数
		}
		for(int i = 1;i<Q+1;i++) {//1~QのNこ
			p[i] = scan.nextInt();
			x[i] = scan.nextInt();
			tyoutenXcount[p[i]]+=x[i];
		}
		DFS(1);
		for(int i = 1;i<=N;i++) {
			System.out.println(tyoutencount[i]);
		}
	}
	private static void DFS(int n) {
		counter+=tyoutenXcount[n];
		tyoutencount[n] +=counter;
		for(int i = 1;i<=N;i++) {
			if(edge[n][i]==1&&tyoutenserch[n]==false) {
				DFS(i);
			}
		}

		counter-=tyoutenXcount[n];
	}
}


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);

        int n_v = Integer.parseInt(sc.next());
        int queri_n = Integer.parseInt(sc.next());
        ArrayList<ArrayList<Integer>> plain_graph = new ArrayList<>(n_v);

        for(int i=0; i<n_v; i++){
            ArrayList<Integer> null_arr = new ArrayList<>(0);
            plain_graph.add(null_arr);
        }

        int a = -1, b = -1;
        for(int i=1; i<n_v; i++){
            a = Integer.parseInt(sc.next())-1;
            b = Integer.parseInt(sc.next())-1;
            plain_graph.get(a).add(b);
            plain_graph.get(b).add(a);
        }

        ArrayList<ArrayList<Integer>> null_arrX2 = new ArrayList<>(n_v);
        for(int i=0; i<n_v; i++){
            ArrayList<Integer> null_arr = new ArrayList<>(0);
            null_arrX2.add(null_arr);
        }

        ArrayList<ArrayList<Integer>> brunch_dt = know_brunch(plain_graph, -1, 0);
        for(int i=0; i<n_v; i++){
            System.out.print(i + ":");
            for(int j=0; j<brunch_dt.get(i).size(); j++){
                System.out.print(brunch_dt.get(i).get(j));
            }
            System.out.println();
        }
        int[] counter = new int[n_v];
        for(int i=0; i<n_v; i++){
            counter[i] = 0;
        }

        int root_tmp = -1, addition = -1;
        for(int i=0; i<queri_n; i++){
            root_tmp = Integer.parseInt(sc.next())-1;
            addition = Integer.parseInt(sc.next());
            counter = add_all_by_part(brunch_dt, counter, root_tmp, addition);
        }
        System.out.print(counter[0]);
        for(int i=1; i<n_v; i++){
            System.out.print(" " + counter[i]);
        }
        System.out.println();
    }

    static int[] add_all_by_part(ArrayList<ArrayList<Integer>> brunch_dt, int[] counter_former, int root_to_add, int amount_to_add){
        counter_former[root_to_add] += amount_to_add;
        for(int i=0; i<brunch_dt.get(root_to_add).size(); i++){
            counter_former = add_all_by_part(brunch_dt, counter_former, brunch_dt.get(root_to_add).get(i), amount_to_add);
        }

        return counter_former;
    }

    static ArrayList<ArrayList<Integer>> know_brunch(ArrayList<ArrayList<Integer>> plain_graph, int its_root, int now_pos){

        int n_brunch = plain_graph.get(now_pos).size() -1, tmp = -1;

        for(int i=0; i<=n_brunch; i++){
            tmp = plain_graph.get(now_pos).get(i);
            if(tmp != its_root){
                plain_graph = know_brunch(plain_graph, now_pos, tmp);
            }else{
                plain_graph.get(now_pos).remove(i);
                i--;
                n_brunch--;
            }
        }

        return plain_graph;
    }

    /*
    static boolean[][] bfs(boolean[][] state, boolean[][] seen, int x, int y){
        int[] tmpltX = {1,-1,0,0};
        int[] tmpltY = {0,0,1,-1};
        int newX = -1, newY = -1;

        seen[y][x] = true;
        for(int i=0; i < 4; i++){
            newX = x+tmpltX[i];
            newY = y+tmpltY[i];
            if((newX >= 0) && (newY >= 0) && (newX < seen[0].length) && (newY < seen.length) && (!seen[newY][newX]) && state[newY][newX]) seen = bfs(state, seen, newX, newY);
        }
        return seen;
    }

    public static int binarySearchMax(int[] dt, int target){
        int left=-1, right=dt.length;
        int mid=-1;

        while((right-left)>1){
            mid = left + (right-left)/2;

            if(dt[mid] <= target){
                left=mid;
            }else{
                right=mid;
            }
        }
        return left+1;
    }*/
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author silviase
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        DKi solver = new DKi();
        solver.solve(1, in, out);
        out.close();
    }

    static class DKi {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int n = in.nextInt();
            int q = in.nextInt();
            Graph g = new Graph(n);
            for (int i = 0; i < n - 1; i++) {
                g.addUnDirectedEdge(in.nextInt() - 1, in.nextInt() - 1);
            }
            for (int i = 0; i < q; i++) {
                g.addCost(in.nextInt() - 1, in.nextInt());
            }

            // 0から順にdfsをする.
            g.dfs(0, g.getCost(0));

            for (int i = 0; i < n; i++) {
                out.println(g.getCost(i));
            }

        }

    }

    static class Graph {
        private int n;
        private ArrayList<Integer>[] adj;
        private int[] cost;
        private boolean[] visited;

        public Graph(int size) {
            n = size;
            cost = new int[n];
            visited = new boolean[n];
            Arrays.fill(visited, false);
            adj = new ArrayList[n];
            for (int i = 0; i < n; i++) {
                adj[i] = new ArrayList<>();
            }
        }

        public void addEdge(int from, int to) {
            adj[from].add(to);
        }

        public void addUnDirectedEdge(int from, int to) {
            addEdge(from, to);
            addEdge(to, from);
        }

        public void addCost(int index, int value) {
            cost[index] += value;
        }

        public void dfs(int index, int cost) {
            if (visited[index]) {
                return;
            }
            visited[index] = true;
            this.cost[index] = cost;
            ArrayList<Integer> nxtAl = adj[index];
            for (int nxt : nxtAl) {
                dfs(nxt, cost + getCost(nxt));
            }
        }

        public int getCost(int i) {
            return cost[i];
        }

    }
}


import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
class Main{

	static final int MOD = 1000000007;

	static	ArrayList<TreeNode> tree;
	static HashSet<Integer> set;
	static int[] ans;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);			//文字の入力
		int n = sc.nextInt();
		int q = sc.nextInt();
		tree = new ArrayList<TreeNode>();

//		for(int i = 0;i < n;i++){
//			TreeNode node = new TreeNode(i, 0);
//			tree.add(node);
//		}

		for(int i = 0;i < n-1;i++){
			int a = sc.nextInt()-1;
			int b = sc.nextInt()-1;
//			tree.get(a).childlen.add(tree.get(b));			//子ノードの追加
//			tree.get(b).childlen.add(tree.get(a));			//子ノードの追加

		}

		for(int i = 0;i < q;i++){
			int p = sc.nextInt()-1;
			int x = sc.nextInt();
//			tree.get(p).sum += x;
		}
		int counter = 0;

		ans = new int[n];
		set = new HashSet<Integer>();
		set.add(0);
	//	dfs(0, 0);

		for(int i = 0;i < n;i++){
			System.out.println(ans[i]);
		}

	}

	static void dfs(int current,int num){

		ans[current] = num + tree.get(current).sum;
		set.add(current);
		for(TreeNode child:tree.get(current).childlen ){
			if(ans[child.value]== 0){
				dfs(child.value, num +tree.get(current).sum);
			}
		}

	}

	static int upperbond(int k,int min,int[] data){		//kより小さい最大の値をdataの中から探し、返す二分探索
		int max = data.length;
		//		if(min == data.length-1){
		//			if(data[min] > k){
		//				return min;
		//			}
		//		}

		while(max-min > 1){
			int mid = (max+min)/2;
			if(data[mid] >= k){
				max = mid;
			}else{
				min = mid;
			}
		}

		return max;
	}

	static int lowerbond(int k,int min,int[] data){		//kより大きい最小の値をdataの中から探し、返す二分探索
		int max = data.length;

		while(max-min > 1){
			int mid = (max+min)/2;
			if(data[mid] >= k){
				max = mid;
			}else{
				min = mid;
			}
		}
		return min;
	}

	static int gcd(int a,int b){				//最大公約数を返す
		if(b == 0){
			return a;
		}else{
			return gcd(b, a%b);
		}
	}
	static long gcd(long a,long b){
		if(b == 0){
			return a;
		}else{
			return gcd(b, a%b);
		}
	}

	static long lcm (long a, long b) {
		long g = gcd(a,b);
		return a/g*b;
	}

}

class TreeNode{
	int value;
	int sum;
	ArrayList<TreeNode> childlen;

	public TreeNode(int v,int s) {
		this.value = v;
		this.sum = s;
		this.childlen = new ArrayList<TreeNode>();
	}

}

class Edge  implements Comparable{

	int index;
	HashSet<Integer> hen;
	HashSet<Integer> used;
	HashMap<Integer, Integer> map;
	int size;

	public Edge(int index) {
		// TODO 自動生成されたコンストラクター・スタブ
		this.index = index;
		hen = new HashSet();
		used = new HashSet<Integer>();
		map = new HashMap<Integer,Integer>();
	}

	public int compareTo(Object other) {
		Edge otherpair = (Edge)other;

		return   otherpair.hen.size() - hen.size();
	}
}

class Food implements Comparable{

	int minits;
	int score;
	double cospa;

	public Food(int from,int end,double c) {
		this.minits = from;
		this.score = end;
		this.cospa = c;
		// TODO 自動生成されたコンストラクター・スタブ
	}

	@Override
	public int compareTo(Object other) {
		Food otherpair = (Food)other;
		int dif = Double.compare(otherpair.cospa, cospa);
		return   dif;
	}

}

class Pair implements Comparable{
	int from;
	int end;
	public Pair(int from,int end) {
		this.from = from;
		this.end = end;
		// TODO 自動生成されたコンストラクター・スタブ
	}

	@Override
	public int compareTo(Object other) {
		Pair otherpair = (Pair)other;

		return  from - otherpair.from;
	}

}


import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		int q = sc.nextInt();

		Node node[] = new Node[n];
		// 頂点の作成
		for (int i = 0; i < n; i++) {
			node[i] = new Node(i);
		}

		// 辺情報
		for (int i = 0; i < n - 1; i++) {
			int nodeA = sc.nextInt() - 1;
			int nodeB = sc.nextInt() - 1;

			node[nodeA].adjList.add(node[nodeB]);
			node[nodeB].adjList.add(node[nodeA]);
		}

		// 親方向の隣接情報を消す
		//removeParent(0, node);

		/*
		for (int i = 0; i < n; i++) {
			printDebug(node[i]);
		}
		*/

		// カウンター計算
		for (int i = 0; i < q; i++) {
			int subRoot = sc.nextInt() - 1;
			long count = sc.nextLong();

			node[subRoot].count += count;
		}
		dfs(null, node[0], 0);

		for (int i = 0; i < n; i++) {
			System.out.print(node[i].count + " ");
			for (Node adj : node[i].adjList) {
				adj.count += node[i].count;
			}
		}
		System.out.println();
		sc.close();
	}

	private static void dfs(Node parent, Node node, int sum) {
		sum += node.count;
		node.count = sum;
		for (Node adj : node.adjList) {
			if (adj != parent) {
				dfs(node, adj, sum);
			}
		}
	}

	private static void printDebug(Node node) {
		System.out.println("===============================");
		System.out.println("id  = " + node.id);
		System.out.print("adj = ");
		for (Node adj : node.adjList) {
			System.out.print(adj.id + " ");
		}
		System.out.println();
		System.out.println("count = " + node.count);
	}

	private static void removeParent(int id, Node[] node) {
		for (Node adj : node[id].adjList) {
			node[adj.id].adjList.remove(node[id]);
			removeParent(adj.id, node);
		}
	}

	static class Node {
		int id;
		List<Node> adjList;
		long count;

		// コンストラクタ
		public Node(int id) {
			this.id = id;
			this.adjList = new ArrayList<Node>();
			this.count = 0;
		}
	}

}


import java.util.*;
class Main{
  public static void main(String[] args){
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    int q=sc.nextInt();
    Node[] a = new Node[n];
    for(int i=0;i<n;i++){
      a[i]=new Node();
    }
    for(int i=0;i<n-1;i++){
      int aa=sc.nextInt()-1;
      int bb=sc.nextInt()-1;
      a[aa].es.add(bb);
      a[bb].es.add(aa);
    }
    for(int i=0;i<q;i++){
      a[sc.nextInt()-1].v+=sc.nextInt();
    }
    Deque<Node> dq = new ArrayDeque<>();
    dq.addFirst(a[0]);
    a[0].d=true;
    while(!dq.isEmpty()){
      Node hr=dq.pollFirst();
      for(int t:hr.es){
        if(!a[t].d){
          a[t].v+=hr.v;
          dq.addFirst(a[t]);
        }
      }
    }
    for(int i=0;i<n-1;i++){
      System.out.print(a[i].v+" ");
    }
    System.out.println(a[n-1].v);
  }
  static class Node{
    boolean d=false;
    int v=0;
    List<Integer> es = new ArrayList<>();
  }
}


import java.util.ArrayList;
import java.util.Scanner;

public class Main {

	static ArrayList<Integer>[] list;

	static int[] counter;

	static boolean[] flag;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int N = sc.nextInt();
		int Q = sc.nextInt();

		list = new ArrayList[N + 1];
		for(int i = 1;i <= N;i++) {
			list[i] = new ArrayList<Integer>();
		}

		for(int i = 1;i <= N - 1;i++) {
			int a = sc.nextInt();
			int b = sc.nextInt();
			list[a].add(b);
		}

		counter = new int[N + 1];
		for(int i = 1;i <= Q;i++) {
			int p = sc.nextInt();
			int x = sc.nextInt();
			counter[p] += x;
		}
		sc.close();

//		for(int i = 1;i <= N - 1;i++) {
//			System.out.println(list[i]);
//		}
//		for(int i = 1;i <= N;i++) {
//			System.out.println(counter[i]);
//		}

		flag = new boolean[N + 1];
		flag[1] = true;
		dfs(1);

		for(int i = 1;i <= N;i++) {
			System.out.println(counter[i]);
		}

	}

	private static void dfs(int x) {
		for(int y : list[x]) {
//			System.out.print(y);
//			System.out.println(flag[y]);
			if(!flag[y]) {
//				System.out.print(y);
//				System.out.println(counter[y]);
				counter[y] += counter[x];
				flag[y] = true;
				dfs(y);
			}
		}
	}
}


import java.util.*;

public class Main{
    public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);

//////////////////////////////////////////////////////
      int n = sc.nextInt();
      int q = sc.nextInt();

      int[] a = new int[n-1];
      int[] b = new int[n-1];

      for(int i=0;i<n-1;i++){
        a[i] = sc.nextInt();
        b[i] = sc.nextInt();
      }

      //int[] p = new int[q];
      //int[] x = new int[q];

      long[] ans = new long[n+1];

      for(int i=0;i<q;i++){
        ans[sc.nextInt()] += sc.nextInt();
      }

      for(int i=0;i<n-1;i++){
        ans[b[i]] += ans[a[i]];
      }
      for(int i=1;i<n+1;i++){
        System.out.print(ans[i]+" ");
      }

/*
      System.out.print(ans[1]+" ");
      for(int i=2;i<n+1;i++){
        for(int j=0;j<n-1;j++){

          if(b[j]==i){
            ans[i] += ans[a[j]];
            break;
          }

        }
        System.out.print(ans[i]+" ");
      }
*/

//////////////////////////////////////////////////////

    }

}


import java.util.*;

public class Main {
	static Node[] ns;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int Q = sc.nextInt();
		ns = new Node[N];
		for (int i = 0; i < N; i++)
			ns[i] = new Node(i);
		for (int i = 0; i < N - 1; i++) {
			int s = sc.nextInt() - 1;
			int t = sc.nextInt() - 1;
			ns[s].add(ns[t]);
			ns[t].add(ns[s]);
		}
		dfs(ns[0], null);
		for (int i = 0; i < Q; i++) {
			int p = sc.nextInt();
			int x = sc.nextInt();
			ns[p - 1].cnt += x;
		}
		sum(ns[0]);
		String res = "";
		for (Node node: ns)
			res += " " + node.cnt;
		System.out.println(res.substring(1));
	}
	private static void sum(Node node)
	{
		if (node.p != null)
			node.cnt += node.p.cnt;
		for (Node c: node) {
			if (c != node.p) {
				sum(c);
			}
		}
	}
	private static void dfs(Node c, Node p)
	{
		c.p = p;
		for (Node cc: c)
			if (cc != p)
				dfs(cc, c);
	}
	static class Node extends ArrayList<Node>
	{
		Node p;
		int id;
		int cnt = 0;
		Node(int _id) {id = _id;}
	}
}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

public class Main {

	static class Node {
		boolean root=true;
		long v;
		List<Node> cs = new ArrayList<>();

	}

	public static void main(String[] args) {
		int n = (int) sc.nextLong();
		int q = (int) sc.nextLong();

		Node[] nodes = new Node[n + 1];
		for (int i = 1, max = n + 1; i < max; i++) {
			nodes[i] = new Node();
		}

		for (int i = 0, max = n - 1; i < max; i++) {
			int n0 = (int) sc.nextLong();
			int n1 = (int) sc.nextLong();
			nodes[n0].cs.add(nodes[n1]);
			nodes[n1].root = false;
		}

		for (int i = 0; i < q; i++) {
			int ni = (int) sc.nextLong();
			int v = (int) sc.nextLong();
			nodes[ni].v += v;
		}

		addChild(nodes[1], 0);

		for (int i = 1; i < nodes.length; i++) {
			if (i != 1) {
				pw.print(" ");
			}
			pw.print(nodes[i].v);
		}
		pw.println();
		pw.flush();
	}

	static void addChild(Node n, long v) {
		n.v += v;
		for (Node c : n.cs) {
			addChild(c, n.v);
		}
	}

	static final FastScanner sc = new FastScanner();
	static final PrintWriter pw = new PrintWriter(System.out);

	static class FastScanner {
		private final InputStream in = System.in;
		private final byte[] buffer = new byte[1024];
		private int ptr = 0;
		private int buflen = 0;

		private boolean hasNextByte() {
			if (ptr < buflen) {
				return true;
			} else {
				ptr = 0;
				try {
					buflen = in.read(buffer);
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (buflen <= 0) {
					return false;
				}
			}
			return true;
		}

		private int readByte() {
			if (hasNextByte())
				return buffer[ptr++];
			else
				return -1;
		}

		static boolean isPrintableChar(int c) {
			return 33 <= c && c <= 126;
		}

		private void skipUnprintable() {
			while (hasNextByte() && !isPrintableChar(buffer[ptr]))
				ptr++;
		}

		public boolean hasNext() {
			skipUnprintable();
			return hasNextByte();
		}

		public String next() {
			if (!hasNext())
				throw new NoSuchElementException();
			StringBuilder sb = new StringBuilder();
			int b = readByte();
			while (isPrintableChar(b)) {
				sb.appendCodePoint(b);
				b = readByte();
			}
			return sb.toString();
		}

		public long nextLong() {
			if (!hasNext())
				throw new NoSuchElementException();
			long n = 0;
			boolean minus = false;
			int b = readByte();
			if (b == '-') {
				minus = true;
				b = readByte();
			}
			if (b < '0' || '9' < b) {
				throw new NumberFormatException();
			}
			while (true) {
				if ('0' <= b && b <= '9') {
					n *= 10;
					n += b - '0';
				} else if (b == -1 || !isPrintableChar(b)) {
					return minus ? -n : n;
				} else {
					throw new NumberFormatException();
				}
				b = readByte();
			}
		}
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author /\
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        DKi solver = new DKi();
        solver.solve(1, in, out);
        out.close();
    }

    static class DKi {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int n = in.nextInt();
            int q = in.nextInt();
            List<Integer>[] adj = new List[n];
            for (int i = 0; i < n; i++) {
                adj[i] = new ArrayList<>();
            }
            for (int i = 0; i < n - 1; i++) {
                int a = in.nextInt();
                int b = in.nextInt();
                adj[a - 1].add(b - 1);
            }
            long[] added = new long[n];
            while (q-- > 0) {
                int p = in.nextInt() - 1;
                int x = in.nextInt();
                added[p] += x;
            }
            long[] res = new long[n];
            res[0] = added[0];
            dfs(0, res, added, adj);
            StringBuilder sb = new StringBuilder();
            for (long i : res) {
                sb.append(i).append(" ");
            }
            out.print(sb);
        }

        static void dfs(int node, long[] res, long[] added, List<Integer>[] adj) {
            for (int i : adj[node]) {
                res[i] = res[node] + added[i];
                dfs(i, res, added, adj);
            }
        }

    }

    static class Scanner {
        private StringTokenizer st;
        private BufferedReader br;

        public Scanner(InputStream s) {
            br = new BufferedReader(new InputStreamReader(s));
        }

        public Scanner(String s) {
            try {
                br = new BufferedReader(new FileReader(s));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        public String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}


import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class Main {
    public static void main(final String[] args) {
        final Scanner scanner = new Scanner(System.in);
        final int n = scanner.nextInt();
        final int q = scanner.nextInt();

        final Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < n - 1; i++) {
            final int a = scanner.nextInt() - 1;
            final int b = scanner.nextInt() - 1;

            map.computeIfAbsent(a, e -> new ArrayList<>())
                    .add(b);

            map.computeIfAbsent(b, e -> new ArrayList<>())
                    .add(a);
        }

        final int[] answers = new int[n];

        for (int i = 0; i < q; i++) {
            final int node = scanner.nextInt() - 1;
            final int operation = scanner.nextInt();
            answers[node] += operation;
        }

        recursive(map, answers, 0);

        for (final int answer : answers) {
            System.out.print(answer + " ");
        }
    }

    private static void recursive(final Map<Integer, List<Integer>> map, final int[] answers, final int node) {
        for (final int relatedNode : map.get(node)) {
            map.get(relatedNode).remove(node);
            answers[relatedNode] += answers[node];

            recursive(map, answers, relatedNode);

            /*
            final Set<Integer> relatedRelatedNodes = map.get(relatedNode);
            if (relatedRelatedNodes == null) {
                return;
            }

            relatedRelatedNodes.remove(node);
            if (!relatedRelatedNodes.isEmpty()) {
                recursive(map, answers, relatedNode);
            }

             */
        }
    }
}


/**
 * Created at 16:15 on 2019-08-22
 */

import java.io.*;
import java.util.*;

public class Main {

  static FastScanner sc = new FastScanner();
  static Output out = new Output(System.out);

  static final int[] dx = {0, 1, 0, -1};
  static final int[] dy = {-1, 0, 1, 0};

  static final long MOD = (long) (1e9 + 7);
  static final long INF = Long.MAX_VALUE / 2;

  public static class Solver {

    ArrayList<Integer>[] to;
    long[] count;

    public Solver() {

      int N = sc.nextInt();
      int Q = sc.nextInt();

      to = new ArrayList[N];
      for (int i=0; i<N; i++) {
        to[i] = new ArrayList<Integer>();
      }

      for (int i=0; i<N-1; i++) {
        int f = sc.nextInt()-1;
        int t = sc.nextInt()-1;
        to[f].add(t);
      }

      count = new long[N];

      for (int q=0; q<Q; q++) {
        int p = sc.nextInt()-1;
        long x = sc.nextLong();
        count[p] += x;
      }

      culc(0);

      out.print(count, " ");

    }

    void culc(int i) {

      for (int t: to[i]) {
        count[t] += count[i];
        culc(t);
      }

    }

  }

  public static void main(String[] args) {
    new Solver();
    out.flush();
  }

  static class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
      if (ptr < buflen) {
        return true;
      } else {
        ptr = 0;
        try {
          buflen = in.read(buffer);
        } catch (IOException e) {
          e.printStackTrace();
        }
        if (buflen <= 0) {
          return false;
        }
      }
      return true;
    }

    private int readByte() {
      if (hasNextByte()) return buffer[ptr++];
      else return -1;
    }

    private static boolean isPrintableChar(int c) {
      return 33 <= c && c <= 126;
    }

    private void skipUnprintable() {
      while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
    }

    public boolean hasNext() {
      skipUnprintable();
      return hasNextByte();
    }

    public String next() {
      if (!hasNext()) throw new NoSuchElementException();
      StringBuilder sb = new StringBuilder();
      int b = readByte();
      while (isPrintableChar(b)) {
        sb.appendCodePoint(b);
        b = readByte();
      }
      return sb.toString();
    }

    public long nextLong() {
      if (!hasNext()) throw new NoSuchElementException();
      long n = 0;
      boolean minus = false;
      int b = readByte();
      if (b == '-') {
        minus = true;
        b = readByte();
      }
      if (b < '0' || '9' < b) {
        throw new NumberFormatException();
      }
      while (true) {
        if ('0' <= b && b <= '9') {
          n *= 10;
          n += b - '0';
        } else if (b == -1 || !isPrintableChar(b)) {
          return minus ? -n : n;
        } else {
          throw new NumberFormatException();
        }
        b = readByte();
      }
    }

    public int nextInt() {
      return (int) nextLong();
    }

    public int[] nextIntArray(int N, boolean oneBased) {
      if (oneBased) {
        int[] array = new int[N + 1];
        for (int i = 1; i <= N; i++) {
          array[i] = sc.nextInt();
        }
        return array;
      } else {
        int[] array = new int[N];
        for (int i = 0; i < N; i++) {
          array[i] = sc.nextInt();
        }
        return array;
      }
    }

    public long[] nextLongArray(int N, boolean oneBased) {
      if (oneBased) {
        long[] array = new long[N + 1];
        for (int i = 1; i <= N; i++) {
          array[i] = sc.nextLong();
        }
        return array;
      } else {
        long[] array = new long[N];
        for (int i = 0; i < N; i++) {
          array[i] = sc.nextLong();
        }
        return array;
      }
    }
  }

  static class Output extends PrintWriter {

    public Output(PrintStream ps) {
      super(ps);
    }

    public void print(int[] a, String separator) {
      for (int i = 0; i < a.length; i++) {
        if (i == 0) print(a[i]);
        else print(separator + a[i]);
      }
      println();
    }

    public void print(long[] a, String separator) {
      for (int i = 0; i < a.length; i++) {
        if (i == 0) print(a[i]);
        else print(separator + a[i]);
      }
      println();
    }

    public void print(String[] a, String separator) {
      for (int i = 0; i < a.length; i++) {
        if (i == 0) print(a[i]);
        else print(separator + a[i]);
      }
      println();
    }

    public void print(ArrayList a, String separator) {
      for (int i = 0; i < a.size(); i++) {
        if (i == 0) print(a.get(i));
        else print(separator + a.get(i));
      }
      println();
    }
  }

}


import java.io.*;
import java.util.*;

public class Main
{
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    public void go() throws IOException
    {
        StringTokenizer tok = new StringTokenizer(in.readLine());
        int n = Integer.parseInt(tok.nextToken());
        int q = Integer.parseInt(tok.nextToken());
        Node[] nodes = new Node[n];
        for (int i = 0; i < n; i++)
        {
            nodes[i] = new Node();
        }
        for (int i = 0; i < n-1; i++)
        {
            tok = new StringTokenizer(in.readLine());
            int a = Integer.parseInt(tok.nextToken())-1;
            int b = Integer.parseInt(tok.nextToken())-1;
            nodes[a].children.add(nodes[b]);
            nodes[b].children.add(nodes[a]);
        }

        LinkedList<Node> queue = new LinkedList<>();
        queue.add(nodes[0]);
        while (!queue.isEmpty())
        {
            Node curr = queue.remove();
            if (curr.visited)
            {
                continue;
            }
            curr.visited = true;
            Iterator<Node> it = curr.children.iterator();
            while (it.hasNext())
            {
                Node next = it.next();
                if (next.visited)
                {
                    it.remove();
                }
                else
                {
                    queue.add(next);
                }
            }
        }

        for (int i = 0; i < q; i++)
        {
            tok = new StringTokenizer(in.readLine());
            int p = Integer.parseInt(tok.nextToken())-1;
            int x = Integer.parseInt(tok.nextToken());
            nodes[p].value += x;
        }
        update(nodes[0], 0);
        for (int i = 0; i < n; i++)
        {
            if (i != 0)
            {
                out.print(" ");
            }
            out.print(nodes[i].value);
        }
        // out.println();

        out.flush();
        in.close();
    }

    public void update(Node curr, long add)
    {
        curr.value += add;
        for (Node next : curr.children)
        {
            update(next, curr.value);
        }
    }

    public static void main(String[] args) throws IOException
    {
        new Main().go();
    }

    private class Node
    {
        ArrayList<Node> children;
        long value;
        boolean visited;

        public Node()
        {
            children = new ArrayList<>();
        }
    }
}


import java.util.*;
import java.math.BigDecimal;

public class Main {
  public static void main(String[] args) {
    int N, Q;
    Node[] nodes;
    int[] p, x;
    try(Scanner sc = new Scanner(System.in)) {
      N = sc.nextInt();
      Q = sc.nextInt();
      nodes = new Node[N];
      for(int i = 0; i < N-1; i++) {
        int a = sc.nextInt();
        int b = sc.nextInt();
        Node nodeA = nodes[a-1];
        if ( nodeA == null ) {
          nodeA = new Node();
          nodes[a-1] = nodeA;
        }
        Node nodeB = nodes[b-1];
        if ( nodeB == null ) {
          nodeB = new Node();
          nodes[b-1] = nodeB;
        }
        nodeA.addChild(nodeB);
      }
      p = new int[Q];
      x = new int[Q];
      for(int j = 0; j < Q; j++) {
        p[j] = sc.nextInt();
        x[j] = sc.nextInt();
      }
    }
    solve(nodes, p, x);
    System.out.print(nodes[0].getScore());
    for(int i = 1; i < N; i++) {
      System.out.print(" ");
      System.out.print(nodes[i].getScore());
    }
    System.out.println();
  }

  private static void solve(Node[] nodes, int[] p, int[] x) {
    int q = p.length;
    for(int j = 0; j < q; j++) {
      Node tmpRoot = nodes[p[j]-1];
      tmpRoot.addScore(x[j]);
    }
    nodes[0].propagateAll();
  }

  private static class Node {
    private Node[] children;

    private volatile long score;

    public Node() {
      children = new Node[0];
    }

    public void addChild(Node child) {
      int n = this.children.length;
      Node[] newChildren = new Node[n+1];
      System.arraycopy(children, 0, newChildren, 0, n);
      newChildren[n] = child;
      this.children = newChildren;
    }

    public void addScore(long value) {
      score += value;
    }

    public void propagateAll() {
      for( Node child : children ) {
        child.addScore(score);
        child.propagateAll();
      }
    }

    public long getScore() {
      return score;
    }
  }

}


import java.util.*;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class Main {
	static class Node {
		int id;
		Set<Integer> childrenIds = new HashSet<>();
		Set<Node> children = new HashSet<>();
		int counter = 0;

		Node(int id) {
			this.id = id;
		}

		void findChildren(Set<Integer> set) {
			if (set == null) {
				childrenIds.add(this.id);
				for (Node node : children) {
					node.findChildren(this.childrenIds);
				}
			} else {
				this.childrenIds.addAll(set);
				this.childrenIds.add(this.id);
				for (Node node : children) {
					node.findChildren(this.childrenIds);
				}
			}
		}
	}

	public static void main(String[] args) throws IOException {
		InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
		BufferedReader in = new BufferedReader(reader);
		String[] tokens = in.readLine().split(" ");
		int N = Integer.parseInt(tokens[0]);
		int Q = Integer.parseInt(tokens[1]);

		Node[] tree = new Node[N];
		for (int i = 0; i < N; ++i) {
			tree[i] = new Node(i);
		}
		for (int i = 0; i < N - 1; ++i) {
			tokens = in.readLine().split(" ");
			int a = Integer.parseInt(tokens[0]) - 1;
			int b = Integer.parseInt(tokens[1]) - 1;
			tree[a].children.add(tree[b]);
		}
		tree[0].findChildren(null);

		for (int i = 0; i < Q; ++i) {
			tokens = in.readLine().split(" ");
			int p = Integer.parseInt(tokens[0]) - 1;
			int q = Integer.parseInt(tokens[1]);
			for (Node node : tree) {
				if (node.childrenIds.contains(p)) {
					node.counter += q;
				}
			}
		}
		StringBuilder strBuilder = new StringBuilder();
		strBuilder.append(Integer.toString(tree[0].counter));
		for (int i = 1; i < N; ++i) {
			strBuilder.append(" " + Integer.toString(tree[i].counter));
		}
		System.out.println(strBuilder.toString());
	}
}