Search is not available for this dataset
name
stringlengths
2
112
description
stringlengths
29
13k
source
int64
1
7
difficulty
int64
0
25
solution
stringlengths
7
983k
language
stringclasses
4 values
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
#include <bits/stdc++.h> using namespace std; const int MAXN = 5e5 + 10; int x[MAXN], y[MAXN]; int main() { int n, a, b, c, d; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d%d%d%d", &a, &b, &c, &d); x[i] = abs(a); y[i] = abs(b); } puts("YES"); for (int i = 0; i < n; i++) { if ((x[i] & 1) && (y[i] & 1)) puts("1"); else if ((x[i] & 1) && !(y[i] & 1)) puts("2"); else if (!(x[i] & 1) && (y[i] & 1)) puts("3"); else puts("4"); } return 0; }
CPP
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class D { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println("YES"); for(int i=0;i<n;i++) { int a = sc.nextInt(); int b = sc.nextInt(); sc.nextInt();sc.nextInt(); System.out.println((((a%2)+2)%2+(((b%2)+2)%2)*2)+1); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} 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 { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
JAVA
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
#include <bits/stdc++.h> using namespace std; int n; int main() { printf("YES\n"); scanf("%d", &n); while (n--) { int a, b, c, d; scanf("%d%d%d%d", &a, &b, &c, &d); if ((a & 1) && (b & 1)) printf("1\n"); else if (!(a & 1) && (b & 1)) printf("2\n"); else if ((a & 1) && !(b & 1)) printf("3\n"); else printf("4\n"); } return 0; }
CPP
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
#include <bits/stdc++.h> using namespace std; int32_t main() { long long n, a1, b1, a2, b2; cin >> n; cout << "YES" << '\n'; for (long long i = 0; i < n; i++) { cin >> a1 >> b1 >> a2 >> b2; long long x = (a1 & 1) * 2 + (b1 & 1) + 1; cout << x << '\n'; } }
CPP
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
import java.io.*; import java.util.*; public class Main { static FastScanner in; static int n; public static void main(String[] args) throws IOException { // Scanner in = new Scanner(new File("input.txt")); // Scanner in = new Scanner(System.in); in = new FastScanner(System.in); // in = new FastScanner("input.txt"); // System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("out.txt")), true)); n = in.nextInt(); System.out.println("YES"); while (n-- > 0) { int x1 = in.nextInt(); int y1 = in.nextInt(); int x2 = in.nextInt(); int y2 = in.nextInt(); if (x1 % 2 == 0) { if (y1 % 2 == 0) System.out.println(1); else System.out.println(2); } else { if (y1 % 2 == 0) System.out.println(3); else System.out.println(4); } } } } class FastScanner { BufferedReader br; StringTokenizer tokenizer; FastScanner(String fileName) throws FileNotFoundException { this(new FileInputStream(new File(fileName))); } FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String nextLine() throws IOException { tokenizer = null; return br.readLine(); } String next() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = br.readLine(); if (line == null) { return null; } tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } char nextChar() throws IOException { return next().charAt(0); } }
JAVA
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
#include <bits/stdc++.h> using namespace std; int color[500005]; int main() { int n; scanf("%d", &n); int i; int x1, y1, x2, y2; for (i = 0; i < n; i++) { scanf("%d %d %d %d", &x1, &y1, &x2, &y2); if (x1 % 2) { if (y1 % 2) { color[i] = 1; } else { color[i] = 2; } } else { if (y1 % 2) { color[i] = 3; } else { color[i] = 4; } } } puts("YES"); for (i = 0; i < n; i++) { printf("%d\n", color[i]); } return 0; }
CPP
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; cout << "YES" << endl; for (int i = 0; i < n; i++) { int x, y, x1, y1; cin >> x >> y >> x1 >> y1; if (abs(x) % 2 == 0 && abs(y) % 2 == 0) { cout << 1 << endl; } else if (abs(x) % 2 == 1 && abs(y) % 2 == 0) { cout << 2 << endl; } else if (abs(x) % 2 == 0 && abs(y) % 2 == 1) { cout << 3 << endl; } else { cout << 4 << endl; } } return 0; }
CPP
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
#include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); printf("YES\n"); for (int i = 1; i <= n; i++) { int x, y; int a, b; scanf("%d%d%d%d", &x, &y, &a, &b); if ((x & 1) && (y & 1)) cout << 1 << endl; if ((x & 1) && !(y & 1)) cout << 2 << endl; if (!(x & 1) && !(y & 1)) cout << 3 << endl; if (!(x & 1) && (y & 1)) cout << 4 << endl; } }
CPP
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
n = int(input()) print("YES") for i in range(n): a, b, c, d = map(int, input().split()) print(1 + (a % 2) + 2*(b % 2))
PYTHON3
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Random; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; //change to Main! //chhange to TestClass public class Main { 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) { int comp1 = Integer.compare(x, o.x); if (comp1 != 0) { return comp1; } return Integer.compare(y, o.y); } } static int MOD = 1000 * 1000 * 1000 + 7; public static void shuffleArray(int[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; in = new InputReader(inputStream); out = new PrintWriter(outputStream); solve(); out.close(); System.exit(0); } private static InputReader in; private static PrintWriter out; private static void solve() { int n = in.nextInt(); out.println("YES"); for(int i = 0; i < n; i++) { int x1 = in.nextInt(); int y1 = in.nextInt(); int x2 = in.nextInt(); int y2 = in.nextInt(); int color = 2 * (Math.abs(x1) % 2) + Math.abs(y1)%2 + 1; out.println(color); } } public static void swap(int[] tab, int i, int j) { int tmp = tab[i]; tab[i] = tab[j]; tab[j] = tmp; } /* * * */ // -------------------------------------------------------- static int gcd(int n, int m) { if (m == 0) { return n; } return gcd(m, n % m); } 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()); } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
JAVA
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; cout << "YES\n"; while (n--) { int a, b, c, d; cin >> a >> b >> c >> d; cout << 2 * (a & 1) + (b & 1) + 1 << endl; } }
CPP
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
#include <bits/stdc++.h> using namespace std; int x[500010], y[500010]; int main() { int n, a, b; scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%d %d %d %d", &x[i], &y[i], &a, &b); x[i] = abs(x[i]); y[i] = abs(y[i]); } printf("YES\n"); for (int i = 0; i < n; ++i) { if (x[i] % 2 == 0 && y[i] % 2 == 1) printf("1\n"); else if (x[i] % 2 == 1 && y[i] % 2 == 1) printf("2\n"); else if (x[i] % 2 == 1 && y[i] % 2 == 0) printf("3\n"); else printf("4\n"); } return 0; }
CPP
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e6 + 10; long long x1[MAXN], x2[MAXN], yy[MAXN], y2[MAXN]; int32_t main() { long long n; cin >> n; long long mn = 0; for (long long i = 0; i < n; i++) { cin >> x1[i] >> yy[i] >> x2[i] >> y2[i]; mn = min(mn, x1[i]); mn = min(mn, x2[i]); mn = min(mn, yy[i]); mn = min(mn, y2[i]); } cout << "YES\n"; mn *= -1; for (long long i = 0; i < n; i++) { x1[i] += mn; x2[i] += mn; yy[i] += mn; y2[i] += mn; long long x = min(x1[i], x2[i]); long long y = min(yy[i], y2[i]); if (x % 2 == 0 && y % 2 == 0) cout << "1\n"; if (x % 2 == 1 && y % 2 == 0) cout << "2\n"; if (x % 2 == 0 && y % 2 == 1) cout << "3\n"; if (x % 2 == 1 && y % 2 == 1) cout << "4\n"; } return 0; }
CPP
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
n = int(input()) ans = 'YES\n' for i in range(n): x1, y1, x2, y2 = map(int, input().split()) res = (x1 & 1) * 2 + (y1 & 1) + 1 ans += str(res) + '\n' print(ans)
PYTHON3
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
#include <bits/stdc++.h> using namespace std; int main() { int a, b, c, d, n; cin >> n; cout << "YES" << endl; for (int i = 0; i < n; i++) { cin >> a >> b >> c >> d; if (a < 0) a *= -1; if (b < 0) b *= -1; cout << 1 + 2 * (a % 2) + (b % 2) << ' ' << endl; } return 0; }
CPP
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; const int INF = 1e9; const double EPS = 1e-8; int main() { int n; scanf("%d", &(n)); int a, b, c, d; puts("YES"); for (int i = 1; i <= n; i++) { scanf("%d", &(a)), scanf("%d", &(b)); scanf("%d", &(c)), scanf("%d", &(d)); if (a & 1 && b & 1) cout << 1 << endl; else if (a & 1 && !(b & 1)) cout << 2 << endl; else if (!(a & 1) && b & 1) cout << 3 << endl; else cout << 4 << endl; } }
CPP
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
#include <bits/stdc++.h> using namespace std; class rectangle { public: int x1; int x2; int y1; int y2; int color; void handle() { if ((x1 % 2 == 0) && (y1 % 2 == 0)) color = 1; else if ((abs(x1 % 2) == 1) && (y1 % 2 == 0)) color = 2; else if ((x1 % 2 == 0) && (abs(y1 % 2) == 1)) color = 3; else if ((abs(x1 % 2) == 1) && (abs(y1 % 2) == 1)) color = 4; else color = 5; } } Rect[500005]; int main() { int n, m, z, i, j, c = 0; while (cin >> n) { for (i = 0; i < n; ++i) { cin >> Rect[i].x1 >> Rect[i].y1 >> Rect[i].x2 >> Rect[i].y2; Rect[i].handle(); } cout << "YES\n"; for (i = 0; i < n; ++i) { cout << Rect[i].color << endl; } } return 0; }
CPP
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class TimofeyRectangles { void solve() { int n = in.nextInt(); out.println("YES"); for (int i = 0; i < n; i++) { int x = in.nextInt(), y = in.nextInt(); in.nextInt(); in.nextInt(); out.printf("%d%n", ((x & 1) << 1 | (y & 1)) + 1); } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new TimofeyRectangles().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
JAVA
764_D. Timofey and rectangles
One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other. Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible. Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length <image> The picture corresponds to the first example Input The first line contains single integer n (1 ≤ n ≤ 5·105) — the number of rectangles. n lines follow. The i-th of these lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1 < x2 ≤ 109, - 109 ≤ y1 < y2 ≤ 109), that means that points (x1, y1) and (x2, y2) are the coordinates of two opposite corners of the i-th rectangle. It is guaranteed, that all sides of the rectangles have odd lengths and rectangles don't intersect each other. Output Print "NO" in the only line if it is impossible to color the rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color. Otherwise, print "YES" in the first line. Then print n lines, in the i-th of them print single integer ci (1 ≤ ci ≤ 4) — the color of i-th rectangle. Example Input 8 0 0 5 3 2 -1 5 0 -3 -4 2 -1 -1 -1 2 0 -3 0 0 5 5 2 10 3 7 -3 10 2 4 -2 7 -1 Output YES 1 2 2 3 2 2 4 1
2
10
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; cout << "YES\n"; for (int i = 1; i <= n; i++) { int x, y, x2, y2; cin >> x >> y >> x2 >> y2; cout << 1 + 2 * (abs(x) % 2) + (abs(y) % 2) << '\n'; } return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class App { public static PrintWriter out; static int s = Integer.MIN_VALUE; public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); /* My brute force way of doing it. int n = sc.nextInt(); int[] a = new int[n]; for(int i = 0;i<n;i++) { a[i] = sc.nextInt(); } for(int r = 1; r < n; r++) { for(int l = 0;l < r; l++) { s = Math.max(s, f(a,l,r)); } } out.println(s); */ /* * Alright, the function works like this: * You have an array. l, r are the start and end indices within which you perform your calculation. * The calculate takes the first value (a[i]) and finds the absolute difference with the next value (a[i+1]). * From this absolute difference, it subtracts the next absolute difference ( a[i+1],a[i+2]), then adds the next, then subtracts, then adds, ad mortem. * * Now you begin to understand why it's useful to have an array of differences. You simply add the elements in this array! * * The non brute force idea, is to generate all possibilities as fast as possible, using divide and conquer. * It first sets out the two cases, which arise from the fact that the position of the bounds affect the numerical values of the arrays of the differences. * * E.g. if the array is [1,4,2,3,1], then the two possible arrays of differences are: * 1. [3,-2,1,-2] or 2. [-3,2,-1,2] * For bound(0,2), this falls into case 1; 3 + -2 * For bound(1,2), this falls into case 2; 2 * For bound(3,4), this falls into case 2; 2. * For bound(i,whatever), if differenceArray[i] == positive, then that is the case it falls into. * * * * */ int n = sc.nextInt(); long[] arr1 = new long[n-1]; long[] arr2 = new long[n-1]; long[] a = new long[n]; for(int i = 0; i< n ; i++) { a[i] = sc.nextInt(); if(i!=0) { long vv = Math.abs(a[i-1] - a[i]); if(i%2 == 1) { arr1[i-1] = vv; arr2[i-1] = -vv; }else { arr1[i-1] = -vv; arr2[i-1] = vv; } } } out.println(Math.max(find_max(arr1,0,n-2),find_max(arr2,0,n-2))); //Tests //long[] x = new long[] {-4,0}; //out.println(cross(x,0,1,1)); //out.println(find_max(new long[] {-500,1,500,1,-500},0,4)); out.close(); } /* * Here's how find_max works. The basic idea is to compare: * * the greatest possible positive sum returned from the left array, * with the greatest possible positive sum returned from the right array, * with the sum of the combined arrays. * * The bounds will simply fall into place. * If the sum returned from the left array is the greatest greatest value, then the bounds will be within the left array. * Likewise for the right array. * If the sum of the combined arrays (not the sum of the greatest possible positive sums) is the greatest value, then the bounds will be the full array. * * Here's a simple breakdown: * For the array [1,4,2,3,1], the two arrays of differences are: * arr1 = [3,-2,1,-2] or arr2 = [-3,2,-1,2] * * arr1 = [3,-2,1,-2]: * [3,-2] and [1,-2] * [3] and [2] [1] and [-2] * Compare above three Compare above three * ^ returns 3 ^ returns 1 * * Compare 3,1 and sum of [3,-2,1,-2] * ^ returns 3; * Therefore for arr1, the max is 3, and this corresponds to the bounds(0,1); * * */ private static long find_max(long[] arr, int low, int high) { // Some recursion if(high == low) { return arr[low]; } int mid = (low+high)/2; long lm = find_max(arr,low,mid); // huh divide and conquer long rm = find_max(arr,mid+1,high); long com = cross(arr,low,mid,high); // Finding the greatest possible positive sum for this array. com = Math.max(com, lm); // Comparison betwen the three values. com = Math.max(com, rm); return com; } // This function is a helper function that finds the greatest possible positive sum of the array. private static long cross(long[] arr, int low, int mid, int high) { long leftsum = Long.MIN_VALUE; long leftsum1 = Long.MIN_VALUE; long sum = 0; for(int i = mid;i>=low;i--) { sum = sum + arr[i]; if(sum>leftsum1) { leftsum1 = sum; } } long rightsum = Long.MIN_VALUE; long rightsum1 = Long.MIN_VALUE; sum = 0; for(int i = mid + 1;i<=high;i++) { sum = sum + arr[i]; if(sum>rightsum1) { rightsum1 = sum; } } if(rightsum1<=0) { rightsum1 = 0; } return Math.max(0, leftsum1+rightsum1); } private static int f(int[] a,int l, int r) { int sum = 0; for(int i = l; i < r ; i++) { sum = (int) (sum + Math.abs(a[i]-a[i+1]) * Math.pow(-1, i-l)); }; return sum; } } 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
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
n=int(input()) l=list(map(int,input().split())) ma=0 p1=0 p2=0 for i in range(n-1) : if (i+1)%2!=0 : p1=p1+abs(l[i]-l[i+1]) p2=p2-abs(l[i]-l[i+1]) if p2<0 : p2=0 ma=max(p1,ma) else : p2=p2+abs(l[i]-l[i+1]) p1=p1-abs(l[i]-l[i+1]) if p1<0 : p1=0 ma=max(p2,ma) print(ma)
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long arr[] = new long[n+1]; arr[0] = 0; for(int i=1;i<n+1;i++){ arr[i] = sc.nextInt(); } long dp[] = new long[n]; long arrE[] = new long[n]; long arrO[] = new long[n]; for(int i=2;i<=n;i++){ dp[i-1] = Math.abs(arr[i]-arr[i-1]); if(i%2 == 0){ arrE[i-1] = dp[i-1]; arrO[i-1] = -dp[i-1]; }else{ arrO[i-1] = dp[i-1]; arrE[i-1] = -dp[i-1]; } } long max = Integer.MIN_VALUE; for(int i=1;i<n;i++){ arrE[i] = Math.max(arrE[i], arrE[i-1]+arrE[i]); arrO[i] = Math.max(arrO[i],arrO[i-1]+arrO[i]); max = Math.max(arrE[i],max); max = Math.max(arrO[i],max); } System.out.println(max); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.*; public final class B{ public static void main(String[] args) { Scanner scan= new Scanner(System.in); int n=scan.nextInt(); long a=scan.nextInt(); long sum=0,min=0,max=0; long b=0; for (int i=1;i<n ;i++ ) { b=scan.nextInt(); if (i%2==0) { sum+=Math.abs(a-b)*(-1); } else{ sum+=Math.abs(a-b); } max=Math.max(sum,max); min=Math.min(sum,min); a=b; } System.out.print(max-min); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Madi Sovetbekov */ public class snova { public static void main(String[]args){ int n,x,y; Scanner in = new Scanner(System.in); n = in.nextInt(); long nmax=0,nmin=0,s=0,z; x = in.nextInt(); for(int i=1;i<n;i++){ y = in.nextInt(); z = Math.abs(x-y); if(i%2==0) z*=-1; s+=z; nmax = Math.max(s,nmax); nmin = Math.min(s,nmin); x=y; } System.out.println(nmax-nmin); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /** * Created by Lenovo on 21-12-2016. */ public class z { public static ArrayList<ArrayList<String>> ss; public static int visit[]; public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int n=Integer.parseInt(br.readLine()); int arr[]=new int[n]; String s[]=br.readLine().split(" "); for(int i=0;i<n;i++){ arr[i]=Integer.parseInt(s[i]); } if(n==2){ System.out.println(Math.abs(arr[0]-arr[1])); return; } long sume[]=new long[n]; long sumo[]=new long[n]; sume[0]=Math.abs(arr[1]-arr[0]); sumo[0]=0; sumo[1]=Math.abs(arr[2]-arr[1]); for(int i=1;i<n-1;i++){ if(i%2==1){ if(sume[i-1]<0){ sume[i]=-1*Math.abs(arr[i]-arr[i+1]); } else{ sume[i]=-1*Math.abs(arr[i]-arr[i+1])+sume[i-1]; } if(sumo[i-1]<0){ sumo[i]=Math.abs(arr[i]-arr[i+1]); } else{ sumo[i]=Math.abs(arr[i]-arr[i+1])+sumo[i-1]; } } else{ if(sume[i-1]<0){ sume[i]=Math.abs(arr[i]-arr[i+1]); } else{ sume[i]=Math.abs(arr[i]-arr[i+1])+sume[i-1]; } if(sumo[i-1]<0){ sumo[i]=-1*Math.abs(arr[i]-arr[i+1]); } else{ sumo[i]=-1*Math.abs(arr[i]-arr[i+1])+sumo[i-1]; } } } long max=0; for(int i=0;i<n;i++){ long m=Math.max(sumo[i],sume[i]); if(m>max){ max=m; } } System.out.println(max); } public static int binary_search2(ArrayList<Integer> s, int key, int low, int high) { int middle; if (low > high) return (low); middle = (low+high)/2; if (s.get(middle) < key) return( binary_search2(s,key,middle+1,high) ); else return(binary_search2(s,key,low,middle-1) ); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.*; import java.util.*; import java.util.logging.Logger; import static java.lang.System.*; public class o{ static BufferedReader br; static long mod = 998244353; static HashSet<Integer> p = new HashSet<>(); public static void main(String[] args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); int testcCase = 1; // testcCase = cinI(); /// // Scanner sc = new Scanner(System.in); while (testcCase-- > 0) { int n =cinI(); long[] arr =readArray(n,0); long[][] dp = new long[n][2];//0 for + 1 for -ve dp[0][0]=Math.abs(arr[0]-arr[1]); dp[0][1]=0; long max= dp[0][0]; for(int i=1;i<n-1;i++){ long diff = Math.abs(arr[i]-arr[i+1]); dp[i][0]=max(diff,dp[i-1][1]+diff); dp[i][1]=max(0,dp[i-1][0]-diff); max=max(dp[i][0],max(dp[i][1],max)); // System.out.println(diff+" Inde "+i +" "+dp[i][0]+" "+dp[i][1]+" "+max); } System.out.println(max); } } public static long minStart(List<Integer> arr){ // int[] a = new int[arr.size()]; long sum=0; for(int i=0;i<arr.size();i++){ sum+=arr.get(i); } // Arrays.sort(a); long ans =sum*-1; ans+=1; return ans; } public static long min(long a,long b) { return Math.min(a,b); } public static int min(int a,int b) { return Math.min(a,b); } public static int[] readArray(int n,int x ,int z)throws Exception{ int[] arr= new int[n]; // System.out.println(arr.length); String[] ar= cinA(); for(int i =x ;i<n;i++){ // System.out.println(i-x); // int y =getI(ar[i-x]); arr[i]=getI(ar[i-x]); } return arr; } public static long[] readArray(int n,int x )throws Exception{ long[] arr= new long[n]; String[] ar= cinA(); for(int i =x ;i<n+x;i++){ arr[i]=getL(ar[i-x]); } return arr; } public static void arrinit(String[] a,long[] b)throws Exception{ for(int i=0;i<a.length;i++){ b[i]=Long.parseLong(a[i]); } } public static HashSet<Integer>[] Graph(int n,int edge,int directed)throws Exception{ HashSet<Integer>[] tree= new HashSet[n]; for(int j=0;j<edge;j++){ String[] uv = cinA(); int u = getI(uv[0]); int v = getI(uv[1]); if(directed==0){ tree[v].add(u); } tree[u].add(v); } return tree; } public static void arrinit(String[] a,int[] b)throws Exception{ for(int i=0;i<a.length;i++){ b[i]=Integer.parseInt(a[i]); } } static double findRoots(int a, int b, int c) { // If a is 0, then equation is not //quadratic, but linear int d = b * b - 4 * a * c; double sqrt_val = Math.sqrt(Math.abs(d)); // System.out.println("Roots are real and different \n"); return Math.max((double) (-b + sqrt_val) / (2 * a), (double) (-b - sqrt_val) / (2 * a)); } public static String cin() throws Exception { return br.readLine(); } public static String[] cinA() throws Exception { return br.readLine().split(" "); } public static String[] cinA(int x) throws Exception{ return br.readLine().split(""); } public static String ToString(Long x) { return Long.toBinaryString(x); } public static void cout(String s) { System.out.println(s); } public static Integer cinI() throws Exception { return Integer.parseInt(br.readLine()); } public static int getI(String s) throws Exception { return Integer.parseInt(s); } public static long getL(String s) throws Exception { return Long.parseLong(s); } public static long max(long a, long b) { return Math.max(a, b); } public static int max(int a, int b) { return Math.max(a, b); } public static void coutI(int x) { System.out.println(String.valueOf(x)); } public static void coutI(long x) { System.out.println(String.valueOf(x)); } public static Long cinL() throws Exception { return Long.parseLong(br.readLine()); } public static void arrInit(String[] arr, int[] arr1) throws Exception { for (int i = 0; i < arr.length; i++) { arr1[i] = getI(arr[i]); } } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int n, a[100005]; long long b[100005], dpMax[100005], dpMin[100005], ans = (1ll << 63); void setup() { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i <= n - 1; i++) b[i] = abs(a[i] - a[i + 1]); n--; } void xuly() { for (int i = n; i >= 1; i--) { dpMax[i] = -min(dpMin[i + 1], 0ll) + b[i]; dpMin[i] = -max(dpMax[i + 1], 0ll) + b[i]; ans = max(ans, dpMax[i]); } cout << ans; } int main() { iostream::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); setup(); xuly(); return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; long long int n, arr[5000005], arrabs[5000005], arr1[5000005], arr2[5000005], pre1[5000005], pre2[5000005]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); long long int i, j; cin >> n; for (i = 0; i < n; i++) cin >> arr[i]; n--; for (i = 0; i < n; i++) arrabs[i] = llabs(arr[i + 1] - arr[i]); for (i = 0; i < n; i++) { if (i & 1) { arr2[i] = -arrabs[i]; arr1[i] = arrabs[i]; } else { arr2[i] = arrabs[i]; arr1[i] = -arrabs[i]; } } pre1[0] = arr1[0]; pre2[0] = arr2[0]; for (i = 1; i < n; i++) { if (pre1[i - 1] > 0) pre1[i] = arr1[i] + pre1[i - 1]; else pre1[i] = arr1[i]; } for (i = 1; i < n; i++) { if (pre2[i - 1] > 0) pre2[i] = arr2[i] + pre2[i - 1]; else pre2[i] = arr2[i]; } long long int ans = 0; for (i = 0; i < n; i++) { ans = max({ans, pre1[i], pre2[i]}); } cout << ans << '\n'; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int* arr = new int[n]; for (int i = 0; i < n; i++) cin >> arr[i]; int* dp1 = new int[n]; for (int i = 1; i < n; i++) dp1[i] = abs(arr[i - 1] - arr[i]); long long* dp2 = new long long[n]; dp2[0] = 0; for (int i = 1; i < n; i++) { if (i % 2 == 1) dp2[i] = dp2[i - 1] + dp1[i]; else dp2[i] = dp2[i - 1] - dp1[i]; } long long min = 0, max = -1; for (int i = 1; i < n; i++) { if (min > dp2[i]) min = dp2[i]; if (max < dp2[i]) max = dp2[i]; } cout << abs(max - min); return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
n = int(raw_input()) xs = map(int, raw_input().split(' ')) fs = map(lambda (x, y): abs(x - y), zip(xs, xs[1:])) fs_start_even = [fs[i] * (-1) ** i for i in xrange(n - 1)] fs_start_odd = [fs[i] * (-1) ** (i + 1) for i in xrange(n - 1)] ''' Returns the maximum sum of a subarray of the `fs` array that starts at an odd or even index depending on value the `shift` paramenter ''' def max_sum(fs, shift): if shift not in [0, 1]: raise Exception("yebanulsya?") min_sifted_sum = 0 max_shifted_sum = 0 current_sum = 0 for i in xrange(n - 1): current_sum += fs[i] # If current sum is the new minimum and the current subarray ends at an # index that is NOT of the specified `shift`, which means that the # subrray after it will start at an index of the specified `shift` if i % 2 != shift and current_sum < min_sifted_sum: min_sifted_sum = current_sum max_shifted_sum = max(max_shifted_sum, current_sum - min_sifted_sum) return max_shifted_sum max_even_starting_sum = max_sum(fs_start_even, shift=0) max_odd_starting_sum = max_sum(fs_start_odd, shift=1) print max(max_even_starting_sum, max_odd_starting_sum)
PYTHON
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; const long long mod1 = 998244353; const long long inf = 1e18; const long long nax = 100005; long long n, a[nax], b[nax], c[nax]; void solve() { cin >> n; for (long long i = (1); i < (n + 1); i++) cin >> a[i]; for (long long i = (1); i < (n); i++) { b[i] = abs(a[i + 1] - a[i]) * (i % 2 ? -1 : 1); c[i] = -1 * b[i]; } long long sum1 = b[1], sum2 = c[1], best = max(sum1, sum2); for (long long i = (2); i < (n); i++) { sum1 = max(b[i], sum1 + b[i]); best = max(best, sum1); sum2 = max(c[i], sum2 + c[i]); best = max(best, sum2); } cout << best; } signed main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); solve(); return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import sys input = sys.stdin.readline n = int(input()) a = list(map(int,input().split())) d = [0]*n c = [0]*n e = [0]*n x = 1 mx = 0 for i in range(1,n): d[i] = abs(a[i] - a[i-1]) for i in range(1,n): c[i] = max(0,c[i-1] + d[i]*x) e[i] = max(0,e[i-1] + d[i]*(-x)) mx = max(mx,max(c[i],e[i])) x = -x print(mx)
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 9; long long arr[maxn]; long long dp[maxn]; int main() { long long a, b, c, d, e, f, g, h; ios::sync_with_stdio(0); while (cin >> a) { long long ans = -1e16; for (int i = 1; i <= a; i++) { cin >> arr[i]; } g = 0; e = 1; for (int i = 2; i <= a; i++, e *= -1ll) { g += e * abs(arr[i] - arr[i - 1]); ans = max(ans, g); if (g < 0) g = 0; } g = 0; e = 1; for (int i = 3; i <= a; i++, e *= -1ll) { g += e * abs(arr[i] - arr[i - 1]); ans = max(ans, g); if (g < 0) g = 0; } cout << ans << endl; } return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Hieu Le */ 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(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); } long[] deltas = new long[n - 1]; for (int i = 0; i < deltas.length; ++i) { deltas[i] = Math.abs(a[i] - a[i + 1]); } long[] prefix = new long[deltas.length]; prefix[0] = deltas[0]; for (int i = 1; i < prefix.length; ++i) { if (i % 2 == 0) { prefix[i] = prefix[i - 1] + deltas[i]; } else { prefix[i] = prefix[i - 1] - deltas[i]; } } long total = prefix[prefix.length - 1]; long[] suffix = new long[prefix.length]; suffix[0] = total; for (int i = 1; i < suffix.length; ++i) { suffix[i] = total - prefix[i - 1]; } long[] maxSuffix = new long[suffix.length]; long[] minSuffix = new long[suffix.length]; maxSuffix[maxSuffix.length - 1] = Math.max(0, suffix[suffix.length - 1]); minSuffix[minSuffix.length - 1] = Math.min(0, suffix[suffix.length - 1]); for (int i = suffix.length - 2; i >= 0; --i) { maxSuffix[i] = Math.max(suffix[i], maxSuffix[i + 1]); minSuffix[i] = Math.min(suffix[i], minSuffix[i + 1]); } long res = Long.MIN_VALUE; for (int start = 0; start < deltas.length; ++start) { if (start % 2 == 0) { // Minimize suffix. long temp = total - ((start - 1 >= 0) ? prefix[start - 1] : 0) - ((start + 1 < suffix.length) ? minSuffix[start + 1] : 0); res = Math.max(temp, res); } else { // Maximize suffix long temp = total - ((start - 1 >= 0) ? prefix[start - 1] : 0) - ((start + 1 < suffix.length) ? maxSuffix[start + 1] : 0); res = Math.max(-temp, res); } } out.println(res); } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; private static final int BUFFER_SIZE = 32768; public InputReader(InputStream stream) { reader = new BufferedReader( new InputStreamReader(stream), BUFFER_SIZE); 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()); } } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def main(): n = I() a = LI() r = t = abs(a[0]-a[1]) for i in range(3,n,2): t -= abs(a[i-1]-a[i-2]) if t < 0: t = 0 t += abs(a[i]-a[i-1]) if r < t: r = t if n < 3: return r t = abs(a[1]-a[2]) if r < t: r = t for i in range(4,n,2): t -= abs(a[i-1]-a[i-2]) if t < 0: t = 0 t += abs(a[i]-a[i-1]) if r < t: r = t return r print(main())
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; void display(vector<int> &a) { for (int z : a) cout << z << " "; cout << endl; } int dx[4] = {0, 0, 1, -1}; int dy[4] = {1, -1, 0, 0}; const int mod = (int)1e9 + 7; const long long INF64 = 3e18; void smxl(long long &a, long long b) { if (a < b) a = b; } void smnl(long long &a, long long b) { if (a > b) a = b; } void adsl(long long &a, long long b) { a += b; if (a >= mod) a -= mod; } void misl(long long &a, long long b) { a -= b; if (a >= mod) a -= mod; if (a < 0) a += mod; } void smx(long long &a, long long b) { if (a < b) a = b; } void smn(long long &a, long long b) { if (a > b) a = b; } void ads(long long &a, long long b) { a += b; if (a >= mod) a -= mod; } void mis(long long &a, long long b) { a -= b; if (a >= mod) a -= mod; if (a < 0) a += mod; } long long gcd(long long a, long long b) { return (b == 0 ? a : gcd(b, a % b)); } long long egcd(long long a, long long b, long long &x, long long &y) { if (a == 0) { x = 0; y = 1; return b; } long long x1, y1; long long d = egcd(b % a, a, x1, y1); x = y1 - (b / a) * x1; y = x1; return d; } long long mbinp(long long a, long long b) { a %= mod; if (b == 0) return 1; long long ans = mbinp(a, b / 2); long long tmp = (ans * ans) % mod; if (b % 2) return ((tmp * a) % mod); return ((tmp) % mod); } long long binp(long long a, long long b) { if (b == 0) return 1; long long ans = binp(a, b / 2); long long tmp = (ans * ans); if (b % 2) return ((tmp * a)); return ((tmp)); } long long C(int n, int m) { long long ret = 1; for (int i = 1; i <= m; i++) { ret *= (n - i + 1); ret /= i; } return ret; } long long overbinp(long long a, int b) { long long res = 1; while (b) { if (b & 1) { if (res < INF64 / a) res *= a; else return INF64; } if (b > 1) { if (a < INF64 / a) a *= a; else return INF64; } b >>= 1; } return res; } class DSU { vector<int> par; vector<int> siize; public: DSU(int n) { par.resize(n); siize.resize(n); for (int i = 0; i < n; i++) { par[i] = i; siize[i] = 1; } } public: int get(int x) { return (x == par[x] ? x : par[x] = get(par[x])); } public: void merge(int a, int b) { int x = get(a); int y = get(b); if (x == y) return; if (siize[x] < siize[y]) swap(x, y); par[y] = x; siize[x] += siize[y]; } }; class BinaryLift { vector<vector<int> > binlift; int n; public: BinaryLift(vector<int> rnk, vector<int> par) { n = (int)par.size(); binlift.resize(n); for (int i = 0; i < n; i++) binlift[i].resize(20); for (int i = 0; i < n; i++) binlift[i][0] = par[i]; for (int j = 1; j < 20; j++) for (int i = 0; i < n; i++) { if ((1 << j) < rnk[i]) binlift[i][j] = binlift[binlift[i][j - 1]][j - 1]; else binlift[i][j] = -1; } } public: int get_kth_ancestor(int x, int k) { int pt = x; for (int i = 19; i >= 0; i--) { if (pt == -1) exit(0); if (k & (1 << i)) pt = binlift[pt][i]; } return pt; } public: int get_th_ancestor(int x, int k) { int pt = x; for (int i = 19; i >= 0; i--) { if (k & (1 << i)) pt = binlift[pt][i]; } return pt; } }; class SparseTable2D { vector<vector<vector<vector<int> > > > sparse; vector<vector<int> > inp; int m, n; private: int lg2(int x) { int out = 0; while ((1 << out) <= x) out++; return out - 1; } public: int rmin(int x1, int y1, int x2, int y2) { int lenx = x2 - x1 + 1; int lx = lg2(lenx) + 1; int leny = y2 - y1 + 1; int ly = lg2(leny) + 1; return min( min(sparse[lx][x1][ly][y1], sparse[lx][x1][ly][y2 + 1 - (1 << ly)]), min(sparse[lx][x2 + 1 - (1 << lx)][ly][y1], sparse[lx][x2 + 1 - (1 << lx)][ly][y2 + 1 - (1 << ly)])); } public: SparseTable2D(vector<vector<int> > input, string param) { n = input.size(); m = input[0].size(); inp = input; if (param == "min") prepromin(); } private: void prepromin() { int lln, lm; lln = lg2(n) + 1; lm = lg2(m) + 1; sparse.resize(lln); for (int i = 0; i < lln; i++) sparse[i].resize(n); for (int i = 0; i < lln; i++) for (int j = 0; j < n; j++) sparse[i][j].resize(lm); for (int i = 0; i < lln; i++) for (int j = 0; j < n; j++) for (int k = 0; k < lm; k++) sparse[i][j][k].resize(m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) sparse[0][i][0][j] = inp[i][j]; for (int j = 1; j < lm; j++) for (int k = 0; k + (1 << j) - 1 < m; k++) sparse[0][i][j][k] = min(sparse[0][i][j - 1][k], sparse[0][i][j - 1][k + (1 << (j - 1))]); } for (int i = 1; i < lln; i++) for (int j = 0; j + (1 << i) - 1 < n; j++) for (int k = 0; k < lm; k++) for (int h = 0; h < m; h++) sparse[i][j][k][h] = min(sparse[i - 1][j][k][h], sparse[i - 1][j + (1 << (i - 1))][k][h]); } }; class SparseTable { vector<vector<long long> > sparse; int n; vector<int> input; private: int lg2(int x) { int out = 0; while ((1 << out) <= x) out++; return out - 1; } public: int rmaxpos(int left, int right) { int len = right - left + 1; int lg = lg2(len); return (input[sparse[left][lg]] > input[sparse[left + len - (1 << lg)][lg]] ? sparse[left][lg] : sparse[left + len - (1 << lg)][lg]); } public: int rmaxval(int left, int right) { int len = right - left + 1; int lg = lg2(len); return (input[sparse[left][lg]] > input[sparse[left + len - (1 << lg)][lg]] ? input[sparse[left][lg]] : input[sparse[left + len - (1 << lg)][lg]]); } public: int rminpos(int left, int right) { int len = right - left + 1; int lg = lg2(len); return (input[sparse[left][lg]] < input[sparse[left + len - (1 << lg)][lg]] ? sparse[left][lg] : sparse[left + len - (1 << lg)][lg]); } public: int rminval(int left, int right) { int len = right - left + 1; int lg = lg2(len); return (input[sparse[left][lg]] < input[sparse[left + len - (1 << lg)][lg]] ? input[sparse[left][lg]] : input[sparse[left + len - (1 << lg)][lg]]); } public: long long rsum(int left, int right) { long long ans = 0; int pos; while (left <= right) { for (int i = 19; i >= 0; i--) if ((1 << i) <= right - left + 1) { pos = i; break; } ans += sparse[left][pos]; left = left + (1 << pos); } return ans; } public: SparseTable(vector<int> inp, string operation) { input = inp; n = inp.size(); if (operation == "min") prepromin(); else if (operation == "max") prepromax(); else if (operation == "sum") preprosum(); } private: void prepromin() { sparse.resize(n); int x = lg2(n) + 1; for (int i = 0; i < n; i++) sparse[i].resize(x); for (int i = 0; i < n; i++) sparse[i][0] = i; for (int j = 1; j < x; j++) for (int i = 0; i + (1 << (j)) - 1 < n; i++) sparse[i][j] = (input[sparse[i][j - 1]] < input[sparse[i + (1 << (j - 1))][j - 1]] ? sparse[i][j - 1] : sparse[i + (1 << (j - 1))][j - 1]); } void prepromax() { sparse.resize(n); int x = lg2(n) + 1; for (int i = 0; i < n; i++) sparse[i].resize(x); for (int i = 0; i < n; i++) sparse[i][0] = i; for (int j = 1; j < x; j++) for (int i = 0; i + (1 << (j)) - 1 < n; i++) sparse[i][j] = (input[sparse[i][j - 1]] > input[sparse[i + (1 << (j - 1))][j - 1]] ? sparse[i][j - 1] : sparse[i + (1 << (j - 1))][j - 1]); } void preprosum() { sparse.resize(n); int x = lg2(n) + 1; for (int i = 0; i < n; i++) sparse[i].resize(x); for (int i = 0; i < n; i++) sparse[i][0] = input[i]; for (int j = 1; j < x; j++) for (int i = 0; i + (1 << (j)) - 1 < n; i++) sparse[i][j] = sparse[i][j - 1] + sparse[i + (1 << (j - 1))][j - 1]; } }; class Vector { public: pair<long long, long long> x; public: Vector(pair<long long, long long> a, pair<long long, long long> b) { x.first = b.first - a.first; x.second = b.second - a.second; } public: long double getMagnitude() { return sqrtl(x.first * x.first + x.second * x.second); } }; class Line { public: pair<long long, long long> x, y; public: Line(pair<long long, long long> a, pair<long long, long long> b) { x = a; y = b; } private: long double dotProduct(Vector a, Vector b) { return a.x.first * b.x.first + a.x.second * b.x.second; } private: long double crossProduct(Vector a, Vector b) { return a.x.first * b.x.second - a.x.second * b.x.first; } private: long double magnitude(Vector a) { return a.getMagnitude(); } public: long double distanceToA(pair<long long, long long> c) { return dotProduct(Vector(x, y), Vector(x, c)) / magnitude(Vector(x, y)); } public: long double orthogonalDistance(pair<long long, long long> c) { return crossProduct(Vector(x, y), Vector(x, c)) / magnitude(Vector(x, y)); } public: pair<long double, long double> intersection(Line l) { pair<long double, long double> ans; ans.first = (long double)((x.first * y.second - x.second * y.first) * (l.x.first - l.y.first) - (x.first - y.first) * (l.x.first * l.y.second - l.x.second * l.y.first)) / ((x.first - y.first) * (l.x.second - l.y.second) - (x.second - y.second) * (l.x.first - l.y.first)); ans.second = (long double)((x.first * y.second - x.second * y.first) * (l.x.second - l.y.second) - (x.second - y.second) * (l.x.first * l.y.second - l.x.second * l.y.first)) / ((x.first - y.first) * (l.x.second - l.y.second) - (x.second - y.second) * (l.x.first - l.y.first)); return ans; } }; class PruferCode { vector<int> code; vector<pair<int, int> > edges; public: PruferCode(vector<int> cc) { code = cc; findEdges(); } private: void findEdges() { map<int, int> mp; set<int> has; set<int> wait; for (int z : code) { mp[z]++; has.insert(z); } for (int i = 0; i < code.size() + 2; i++) if (!has.count(i)) wait.insert(i); for (int i = 0; i < code.size(); i++) { int now = *wait.begin(); edges.push_back(make_pair(now, code[i])); mp[now]++; mp[code[i]]--; if (mp[code[i]] == 0) { has.erase(code[i]); wait.insert(code[i]); } wait.erase(now); } assert(wait.size() == 2); edges.push_back(make_pair(*wait.begin(), *wait.rbegin())); } public: vector<pair<int, int> > getEdges() { return edges; } }; class Segment { pair<long long, long long> x, y; public: Segment(pair<long long, long long> a, pair<long long, long long> b) { x = a; y = b; } private: long double dotProduct(Vector a, Vector b) { return a.x.first * b.x.first + a.x.second * b.x.second; } private: long double crossProduct(Vector a, Vector b) { return a.x.first * b.x.second - a.x.second * b.x.first; } private: long double magnitude(Vector a) { return a.getMagnitude(); } public: long double distanceToA(pair<long long, long long> c) { return dotProduct(Vector(x, y), Vector(x, c)) / magnitude(Vector(x, y)); } public: long double distanceToSegment(pair<long long, long long> c) { if (distanceToA(c) >= 0 && distanceToA(c) <= magnitude(Vector(x, y))) return crossProduct(Vector(x, y), Vector(x, c)) / magnitude(Vector(x, y)); else return min(magnitude(Vector(x, c)), magnitude(Vector(y, c))); } }; class HopcroftKarp { vector<int> matched; vector<vector<pair<int, int> > > adj; int left; int right; public: HopcroftKarp(vector<vector<pair<int, int> > > inp, int l, int r) { adj = inp; left = l; matched.resize(l); for (int i = 0; i < l; i++) matched[i] = -1; right = r; } public: vector<int> match() { bool cont = true; set<int> lfree, rfree; for (int i = 0; i < left; i++) lfree.insert(i); for (int i = left; i < left + right; i++) rfree.insert(i); vector<bool> yet(left, 0); for (int i = 0; i < left; i++) for (int j = 0; j < adj[i].size(); j++) if (adj[i][j].second == 1 && rfree.count(adj[i][j].first) && !yet[i]) { yet[i] = true; matched[i] = adj[i][j].first; adj[i][j].second = 2; for (int x = 0; x < adj[adj[i][j].first].size(); x++) if (adj[adj[i][j].first][x].first == i) adj[adj[i][j].first][x].second = 2; rfree.erase(adj[i][j].first); lfree.erase(i); } while (cont) { vector<int> par(left + right, -1); queue<pair<int, int> > kyou; for (int z : lfree) kyou.push(make_pair(z, 0)); int update = -1; vector<int> vis(left + right, 0); while (kyou.size()) { pair<int, int> frt = kyou.front(); kyou.pop(); if (rfree.count(frt.first)) { update = frt.first; break; } if (frt.second == 0) { for (pair<int, int> z : adj[frt.first]) { if (z.second == 1 && !vis[z.first]) { par[z.first] = frt.first; vis[z.first] = 1; kyou.push(make_pair(z.first, 1)); } } } else { for (pair<int, int> z : adj[frt.first]) { if (z.second == 2 && !vis[z.first]) { par[z.first] = frt.first; vis[z.first] = 1; kyou.push(make_pair(z.first, 0)); } } } } int x = update; int cnt = 0; while (x != -1 && par[x] != -1) { for (int i = 0; i < adj[x].size(); i++) if (adj[x][i].first == par[x]) { adj[x][i].second = (cnt == 0 ? 2 : 1); if (cnt == 0) { matched[par[x]] = x; rfree.erase(x); lfree.erase(par[x]); } } for (int i = 0; i < adj[par[x]].size(); i++) if (adj[par[x]][i].first == x) adj[par[x]][i].second = (cnt == 0 ? 2 : 1); cnt++; cnt %= 2; x = par[x]; } if (update == -1) cont = false; } return matched; } }; class Triangle { pair<long long, long long> x, y, z; public: Triangle(pair<long long, long long> a, pair<long long, long long> b, pair<long long, long long> c) { x = a; y = b; z = c; } private: long double crossProduct(Vector a, Vector b) { return a.x.first * b.x.second - a.x.second * b.x.first; } public: long double perimeter() { long double s1, s2, s3; s1 = Vector(x, y).getMagnitude(); s2 = Vector(y, z).getMagnitude(); s3 = Vector(x, z).getMagnitude(); return s1 + s2 + s3; } public: long double area() { return abs(crossProduct(Vector(x, y), Vector(x, z))); } }; class SuffixArray { vector<int> order; vector<int> lcp; string str; public: SuffixArray(string in) { str = in; str += '$'; order.resize(str.length()); lcp.resize(str.length()); compute(); } void compute() { vector<pair<char, int> > a; vector<int> equi(order.size()); vector<int> bij(order.size()); for (int i = 0; i < str.length(); i++) a.push_back(make_pair(str[i], i)); sort(a.begin(), a.end()); for (int i = 0; i < str.length(); i++) order[i] = a[i].second; equi[order[0]] = 0; int r = 0; for (int i = 1; i < str.length(); i++) { if (a[i].first == a[i - 1].first) equi[order[i]] = r; else equi[order[i]] = ++r; } int k = 0; while ((1 << k) < str.length()) { vector<pair<pair<int, int>, int> > a(str.length()); for (int i = 0; i < str.length(); i++) a[i] = make_pair( make_pair(equi[i], equi[(i + (1 << k)) % (str.length())]), i); sort(a.begin(), a.end()); for (int i = 0; i < str.length(); i++) { order[i] = a[i].second; bij[order[i]] = i; } int r = 0; equi[order[0]] = 0; for (int i = 1; i < str.length(); i++) { if (a[i].first == a[i - 1].first) equi[order[i]] = r; else equi[order[i]] = ++r; } k++; } k = 0; for (int i = 0; i < str.length() - 1; i++) { int p = bij[i]; int j = order[p - 1]; while (i + k < str.length() && j + k < str.length() && str[i + k] == str[j + k]) k++; lcp[p] = k; k = max(k - 1, 0); } } public: int count(string ptr) { int low = 0; int hi = str.length() - 1; int res1, res2; res1 = 0; res2 = 1e9; while (low <= hi) { int mid = (low + hi) / 2; bool gr = false; int i = 0; for (i; i < min(ptr.length(), str.length() - order[mid]); i++) { if (ptr[i] != str[order[mid] + i]) { if (ptr[i] > str[order[mid] + i]) gr = true; break; } } if (i == ptr.length()) { res2 = min(res2, mid); hi = mid - 1; } else if (!gr) hi = mid - 1; else low = mid + 1; } low = 0; hi = str.length() - 1; while (low <= hi) { int mid = (low + hi) / 2; bool gr = false; int i = 0; for (i; i < min(ptr.length(), str.length() - order[mid] + 1); i++) { if (ptr[i] != str[order[mid] + i]) { if (ptr[i] > str[order[mid] + i]) gr = true; break; } } if (i == ptr.length()) { res1 = max(res1, mid); low = mid + 1; } else if (!gr) hi = mid - 1; else low = mid + 1; } if (res2 == 1e9) return 0; return (res1 - res2 + 1); } public: vector<int> get() { return order; } public: vector<int> getLcp() { return lcp; } public: long long diffSubstrings() { long long out = 0; for (int i = 1; i < str.length(); i++) out += str.length() - order[i] - lcp[i] - 1; return out; } }; string longestCommonSubstring(string a, string b) { int len = 0; string res = a + '%' + b; SuffixArray sf = SuffixArray(res); vector<int> order = sf.get(); vector<int> lcp = sf.getLcp(); vector<int> col(order.size()); for (int i = 0; i < order.size(); i++) { if (order[i] < a.length()) col[order[i]] = 1; else if (order[i] > a.length()) col[order[i]] = 2; } int pos = -1; for (int i = 1; i < order.size(); i++) if (col[order[i]] + col[order[i - 1]] == 3) { if (lcp[i] > len) { len = max(len, lcp[i]); pos = (col[order[i]] == 1 ? order[i] : order[i - 1]); } } return a.substr(pos, len); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; vector<long long> all(n); for (int i = 0; i < n; i++) cin >> all[i]; vector<long long> diff; for (int i = 0; i < n; i++) diff.push_back(abs(all[i] - all[i - 1]) * (i % 2 ? 1 : -1)); vector<long long> pref(n, 0); for (int i = 1; i < n; i++) pref[i] = pref[i - 1] + diff[i]; long long mn, mx; mn = 1e18; mx = -1e18; for (int i = 0; i < pref.size(); i++) { mn = min(mn, pref[i]); mx = max(mx, pref[i]); } cout << abs(mn - mx); }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const long long infl = 1e15 + 5; long long int m, n, p, q, x, y, k, mx = 0, mn = 0, f, val, sz, sm, cnt, ans, t = 1, i, j, ind = -1; long long int a[300004], cur; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); if (fopen("inp.txt", "r")) { freopen("myfile.txt", "w", stdout); freopen("inp.txt", "r", stdin); } cin >> n; for (i = 1; i < n + 1; i++) { cin >> a[i]; } for (i = 1; i < n; i++) { if ((i - 1) % 2 == 0) cur += abs(a[i] - a[i + 1]); else cur -= abs(a[i] - a[i + 1]); if (cur > mx) mx = cur; if (cur < 0) cur = 0; } cur = 0; for (i = 1; i < n; i++) { if ((i - 1) % 2 == 1) cur += abs(a[i] - a[i + 1]); else cur -= abs(a[i] - a[i + 1]); if (cur > mn) mn = cur; if (cur < 0) cur = 0; } cout << max(mx, mn); return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
n = int(input()) a = list(map(int, input().split())) a = [abs(a[i] - a[i + 1]) for i in range(n - 1)] ans = t1 = t2 = 0 for i in a: t1, t2 = max(t2 + i, 0), max(t1 - i, 0) ans = max(ans,t1,t2) print(ans)
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ; long long n; cin >> n; vector<long long> a(n); for (long long i = 0; i < n; i++) { cin >> a[i]; } vector<long long> prefix(n); prefix[0] = -1; prefix[1] = abs(a[0] - a[1]); for (long long i = 2; i < n; i++) { if (i % 2 == 0) { prefix[i] = prefix[i - 1] - abs(a[i - 1] - a[i]); } else { prefix[i] = prefix[i - 1] + abs(a[i - 1] - a[i]); } } long long min_till_now = prefix[1], max_till_now = prefix[1]; long long answer = prefix[1]; long long curr_answer = prefix[1]; for (long long r = 2; r < n; r++) { answer = max(answer, prefix[r] - min_till_now); answer = max(answer, max_till_now - prefix[r]); answer = max(answer, prefix[r]); if (prefix[r] < min_till_now) min_till_now = prefix[r]; if (prefix[r] > max_till_now) max_till_now = prefix[r]; } cout << answer << "\n"; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int arr [] = new int[n]; long dp [] = new long[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } dp[n - 1] = 0; dp[n - 2] = Math.abs(arr[n - 2] - arr[n - 1]); long max = dp[n - 2]; for (int i = n - 3; i >= 0; i--) { dp[i] = Math.max(Math.abs(arr[i] - arr[i + 1]), dp[i + 2] + Math.abs(arr[i] - arr[i + 1]) - Math.abs(arr[i + 1] - arr[i + 2])); max = Math.max(dp[i], max); } out.println(max); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; 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 String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; long long aa[100005]; int main() { int n; long long m1, a, m2; cin >> n; for (int i = 0; i < n; i++) cin >> aa[i]; for (int i = 0; i < n - 1; i++) aa[i] = abs(aa[i] - aa[i + 1]); m1 = m2 = a = 0; for (int i = 0; i < n - 1; i++) { if (i % 2) a -= aa[i]; else a += aa[i]; if (a < 0) a = 0; m1 = max(a, m1); } a = 0; for (int i = 1; i < n - 1; i++) { if (i % 2) a += aa[i]; else a -= aa[i]; if (a < 0) a = 0; m2 = max(a, m2); } cout << max(m1, m2); return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; signed main() { ios::sync_with_stdio(false); cin.tie(NULL); long long n; cin >> n; vector<long long> v(n), pr1(n), pr2(n); for (long long i = 0; i < n; i++) { cin >> v[i]; } for (long long i = 1; i < n; i++) { if (i & 1) { pr2[i] = -1 * abs(v[i] - v[i - 1]); pr1[i] = abs(v[i] - v[i - 1]); } else { pr1[i] = -1 * abs(v[i] - v[i - 1]); pr2[i] = abs(v[i] - v[i - 1]); } } long long ans = pr1[1], z = pr1[1]; for (long long i = 2; i < n; i++) { z += pr1[i]; ans = max(z, ans); if (z < 0) z = 0; } if (n > 2) z = pr2[2]; ans = max(z, ans); for (long long i = 3; i < n; i++) { z += pr2[i]; ans = max(z, ans); if (z < 0) z = 0; } cout << ans << "\n"; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
def main(): n = int(input()) a = list(map(int, input().split())) b = [abs(a[i] - a[i + 1]) for i in range(len(a) - 1)] ansmx = [0] * len(b) ansmn = [0] * len(b) ansmx[-1] = b[-1] ansmn[-1] = 0 for i in range(1, len(b)): j = i - 1 ansmx[-1 - i] = b[-1 - i] - ansmn[-i] ansmn[-1 - i] = min(b[-1 - i] - ansmx[-i], 0) print(max(ansmx)) if __name__ == "__main__": main()
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class A { public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); int []a=new int [n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); long [][]dp=new long [n][2]; for(int i=n-2;i>=0;i--) { int x=Math.abs(a[i]-a[i+1]); dp[i][0]=dp[i][1]=0; dp[i][0]=Math.max(dp[i][0], dp[i+1][1]+x); dp[i][1]=Math.max(dp[i][1], dp[i+1][0]-x); } long ans=0; for(int i=0;i<n-1;i++) ans=Math.max(ans,Math.max(dp[i][0], dp[i][1])); pw.println(ans); pw.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner( String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(s)); } 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 boolean ready() throws IOException { return br.ready(); } } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import os import sys from io import BytesIO, IOBase import heapq as h from bisect import bisect_left from types import GeneratorType BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") import time start_time = time.time() import collections as col import math, string from functools import reduce def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input() def listStr(): return list(input()) MOD = 10**9+7 """ """ def solve(): N = getInt() A = getInts() diffs = [pow(-1,j)*abs(A[j]-A[j+1]) for j in range(N-1)] curr = 0 P = [] for d in diffs: curr += d P.append(curr) min_x = min(P) max_x = max(P) return max(abs(max_x),abs(min_x),abs(max_x-min_x)) #for _ in range(getInt()): print(solve())
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.*; import java.io.*; public class Solution { static FastScanner scr=new FastScanner(); // static Scanner scr=new Scanner(System.in); static PrintStream out=new PrintStream(System.out); static StringBuilder sb=new StringBuilder(); static class pair{ int x;int y; pair(int x,int y){ this.x=x;this.y=y; } } static class triplet{ int x; long y; int z; triplet(int x,long y,int z){ this.x=x; this.y=y; this.z=z; } } 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(); } long gcd(long a,long b){ if(b==0) { return a; } return gcd(b,a%b); } int[] sort(int a[]) { int multiplier = 1, len = a.length, max = Integer.MIN_VALUE; int b[] = new int[len]; int bucket[]; for (int i = 0; i < len; i++) if (max < a[i]) max = a[i]; while (max / multiplier > 0) { bucket = new int[10]; for (int i = 0; i < len; i++) bucket[(a[i] / multiplier) % 10]++; for (int i = 1; i < 10; i++) bucket[i] += (bucket[i - 1]); for (int i = len - 1; i >= 0; i--) b[--bucket[(a[i] / multiplier) % 10]] = a[i]; for (int i = 0; i < len; i++) a[i] = b[i]; multiplier *= 10; } return a; } long modPow(long base,long exp) { if(exp==0) { return 1; } if(exp%2==0) { long res=(modPow(base,exp/2)); return (res*res); } return (base*modPow(base,exp-1)); } int []reverse(int a[]){ int b[]=new int[a.length]; int index=0; for(int i=a.length-1;i>=0;i--) { b[index]=a[i]; } return b; } 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; } long nextLong() { return Long.parseLong(next()); } } static ArrayList<pair>a; static int prime[]; static void solve() { int n=scr.nextInt(); int []a=scr.readArray(n); int pref[]=new int[n-1]; for(int i=0;i<n-1;i++) { pref[i]=Math.abs(a[i]-a[i+1]); if((i%2==1)) { pref[i]=-pref[i]; } } long max=pref[0]; long currMax=pref[0]; for(int i=1;i<n-1;i++) { currMax=Math.max(pref[i], currMax+pref[i]); max=Math.max(currMax, max); // out.println(max); } currMax=-pref[0]; max=Math.max(max, currMax); for(int i=1;i<n-1;i++) { currMax=Math.max(-pref[i], currMax-pref[i]); max=Math.max(currMax, max); } out.println(max); } static int MAX = Integer.MAX_VALUE; static int MIN = Integer.MIN_VALUE; public static void main(String []args) { // int t=scr.nextInt(); // while(t-->0) { // solve(); // } solve(); out.println(sb); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
def mp(): return map(int,input().split()) def lt(): return list(map(int,input().split())) def pt(x): print(x) def ip(): return input() def it(): return int(input()) def sl(x): return [t for t in x] def spl(x): return x.split() def aj(liste, item): liste.append(item) def bin(x): return "{0:b}".format(x) def listring(l): return ' '.join([str(x) for x in l]) def ptlist(l): print(' '.join([str(x) for x in l])) n = it() a = lt() L = [abs(a[i]-a[i+1]) for i in range(n-1)] ans = [0 for _ in range(n)] ans[0] = L[0] for i in range(1,n-1): ans[i] = max(L[i],L[i]-ans[i-1]) if i-2 >= 0: ans[i] = max(ans[i],L[i]-L[i-1]+ans[i-2]) print(max(ans))
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { int n; cin >> n; int a[100002] = {}; for (int i = 0; i < n; i++) { cin >> a[i]; } long long ans1 = 0, ans2 = 0; long long ans; for (int i = 1; i < n; i++) { long long v = abs(a[i] - a[i - 1]); if (i % 2 == 0) { ans1 = max(ans1 + v, v); ans2 = ans2 - v; } else { ans1 = ans1 - v; ans2 = max(ans2 + v, +v); } ans = max(ans, max(ans1, ans2)); } cout << ans; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
n=int(input()) a=list(map(int,input().split())) l=[abs(a[i+1]-a[i]) for i in range(n-1)] dp=[[0,0] for i in range(n-1)] dp[0][0]=l[0] ans=max(dp[0]) for i in range(1,n-1): dp[i]=[max(dp[i-1][1]+l[i],l[i]),max(dp[i-1][0]-l[i],-l[i])] ans=max(ans,max(dp[i])) print(ans)
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
n = int(raw_input()) a = map(int, raw_input().split()) b = [] for i in xrange(len(a) - 1): b.append(abs(a[i] - a[i+1])) b1 = [] p1 = [0] for i in xrange(len(b)): b1.append(b[i] if i % 2 == 0 else -b[i]) p1.append(p1[i] + b1[i]) b2 = [-r for r in b1] p2 = [-p for p in p1] mp1 = [p for p in p1] mp2 = [p for p in p2] #print b1, b2 #print p1, p2 for j in xrange(len(p2) - 2, -1, -1): mp1[j] = (max(mp1[j+1], p1[j])) mp2[j] = (max(mp2[j+1], p2[j])) mv = float('-inf') for i in xrange(1, len(p1)-1): mv = max(mp1[i+1] - p1[i-1], mv) for i in xrange(2, len(p2) - 1): mv = max(mp2[i+1] - p2[i-1], mv) mv = max(max(b), mv) print mv
PYTHON
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.*; import java.lang.*; import java.io.*; public class Main { void run() throws Exception { int n = nextInt(); int[] vals = new int[n]; for(int i = 0; i < n; i++) vals[i] = nextInt(); long[] diff = new long[n-1]; for(int i = 0; i < n-1; i++) diff[i] = Math.abs(vals[i]-vals[i+1]); long[][] dp = new long[n-1][2]; // odd/even starting index 0 = even dp[0][0] = diff[0]; dp[0][1] = Integer.MIN_VALUE/2; for(int i = 1; i < n-1; i++) { if(0 == i % 2) { dp[i][0] = Math.max(dp[i-1][0], 0) + diff[i]; dp[i][1] = Math.max(dp[i-1][1], 0) - diff[i]; } else { dp[i][0] = Math.max(dp[i-1][0], 0) - diff[i]; dp[i][1] = Math.max(dp[i-1][1], 0) + diff[i]; } } long max = 0; for(int i = 0; i < n-1; i++) { max = Math.max(max, dp[i][0]); max = Math.max(max, dp[i][1]); } out.println(max); in.close(); out.close(); } public static void main(String args[]) throws Exception { new Main().run(); // read from stdin/stdout // new Main("filename.in", "filename.out").run(); // or use file i/o } BufferedReader in; PrintWriter out; StringTokenizer st; Main() throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); // in = new BufferedReader(new FileReader(new File(is))); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));; } Main(String inn, String ot) throws Exception { in = new BufferedReader(new FileReader(new File(inn))); out = new PrintWriter(new BufferedWriter(new FileWriter(new File(ot)))); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
N = int(input()) L = list(map(int, input().split())) if N == 2: print(abs(L[0] - L[1])) exit() M = [] for i in range(N - 1): M.append(abs(L[i] - L[i + 1])) M1 = [0] flg = True for i in range(N - 1): if flg: M1.append(M1[-1] + M[i]) else: M1.append(M1[-1] - M[i]) flg = not flg M2 = [0] flg = True for i in range(1, N - 1): if flg: M2.append(M2[-1] + M[i]) else: M2.append(M2[-1] - M[i]) flg = not flg def get_max(lst): maxv = 0 minv = lst[0] for l in lst: maxv = max(maxv, l - minv) minv = min(minv, l) return maxv ans = max(get_max(M1), get_max(M2)) print(ans)
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Wolfgang Beyer */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); long[] a = in.readLongArray(n); long[] diff = new long[n - 1]; for (int i = 0; i < n - 1; i++) { diff[i] = Math.abs(a[i] - a[i + 1]); } long sum = 0; long sum2 = 0; long maxSum = 0; for (int i = 0; i < n - 1; i++) { long current = diff[i]; if (i % 2 == 1) { current = -current; } sum += current; sum2 -= current; if (sum < 0) { sum = 0; } if (sum2 < 0) { sum2 = 0; } maxSum = Math.max(maxSum, sum); maxSum = Math.max(maxSum, sum2); } out.println(maxSum); } } static class InputReader { private static BufferedReader in; private static StringTokenizer tok; public InputReader(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public long[] readLongArray(int n) { long[] ar = new long[n]; for (int i = 0; i < n; i++) { ar[i] = nextLong(); } return ar; } public String next() { try { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } } catch (IOException ex) { System.err.println("An IOException was caught :" + ex.getMessage()); } return tok.nextToken(); } } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const int mx = 1e5 + 7; int a[mx]; long long dp[mx][2]; int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i < n; i++) a[i] = abs(a[i] - a[i + 1]); long long ans = 0; for (int i = 1; i < n; i++) { dp[i][0] = max(dp[i][0], dp[i - 1][1] + a[i]); dp[i][1] = max(dp[i][1], dp[i - 1][0] - a[i]); ans = max(ans, max(dp[i][0], dp[i][1])); } printf("%lld\n", ans); return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; using ll = long long; using ull = unsigned long long; using ld = long double; using vi = vector<ll>; using vs = vector<string>; using ii = pair<ll, ll>; using ss = pair<string, string>; using ldld = pair<ld, ld>; template <typename X> istream& operator>>(istream& stream, vector<X>& vec) { for (auto& e : vec) stream >> e; return stream; } template <typename X, typename Y> istream& operator>>(istream& stream, pair<X, Y>& p) { stream >> p.first >> p.second; return stream; } template <typename X, typename Y> Y& operator<<(Y& str, const vector<X>& vec) { for (auto& e : vec) str << e; return str; } template <typename X, typename Y> Y& operator<<(Y& str, const set<X>& vec) { for (auto& e : vec) str << e; return str; } template <typename X, typename Y> Y& operator<<(Y& str, const list<X>& vec) { for (auto& e : vec) str << e; return str; } template <typename X, typename Y> Y& operator<<(Y& str, const deque<X>& vec) { for (auto& e : vec) str << e; return str; } template <typename X, typename Y, typename Z> Z& operator<<(Z& str, const pair<X, Y>& p) { str << p.first << p.second; return str; } struct sep { sep(string sep) : _(sep) {} string _; }; struct sep_ostream { sep_ostream(ostream& str, string sep) : _str(str), _sep(sep) {} template <typename X> sep_ostream& operator<<(const X& a) { if (_step-- > 1) { *this << a; } else _str << (_step ? _sep : "") << a; return *this; } sep_ostream& operator<<(ostream& (*manip)(ostream&)) { manip(_str); return *this; } private: ostream& _str; string _sep; int _step = 2; }; sep_ostream operator<<(ostream& str, sep s) { return sep_ostream(str, s._); } struct debug_stream { debug_stream(sep_ostream str) : _str(str) {} ~debug_stream() {} template <typename X> debug_stream& operator<<(const X& a) { return *this; } debug_stream& operator<<(ostream& (*manip)(ostream&)) { return *this; } debug_stream& operator()(string pre) { return *this; } private: sep_ostream _str; }; using namespace chrono; struct debug_time { debug_time(sep_ostream str) : _str(str), start(system_clock::now()) {} ~debug_time() {} private: sep_ostream _str; time_point<system_clock> start; }; struct X { ll low; ll high; ll sum; }; ll kad(vi& x, ll low, ll high) { ll res = x[low], sum = 0; for (ll i = low; i < high; ++i) { sum += x[i]; sum = max(sum, 0ll); res = max(res, sum); } return res; } int main() { ll n; cin >> n; vi a(n); cin >> a; auto calc = [&](bool x) { auto elem = [&](ll i, ll l) { return abs(a[i] - a[i + 1]) * pow(-1, i - l); }; ll res = elem(0, 0); ll sum = 0; ll left = !x; for (ll i = 0; i < n - 1; ++i) { debug_stream(sep_ostream(cout, " ")) << i << left << sum << elem(i, left); sum += elem(i, left); if (sum <= 0ll) { left = i + 1; if (left % 2 == x) { i++; left++; } sum = 0; } res = max(res, sum); } return res; }; cout << max(calc(true), calc(false)); }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 8; long long a[MAXN], b[MAXN]; int main() { ios::sync_with_stdio(false); cin.tie(0); long long n, x, y, i; cin >> n; for (i = 1; i <= n; i++) { cin >> x; if (i > 1) { if (i % 2 == 0) { a[i - 1] = abs(x - y); b[i - 1] = -abs(x - y); } else { a[i - 1] = -abs(x - y); b[i - 1] = abs(x - y); } y = x; } else { y = x; } } long long last = 0, ans = 0; for (i = 1; i < n; i++) { last = max((long long)0, last) + a[i]; ans = max(ans, last); } last = 0; for (i = 2; i < n; i++) { last = max((long long)0, last) + b[i]; ans = max(ans, last); } cout << ans << endl; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) cin >> a[i]; int b[n]; b[0] = 0; for (int i = 1; i < n; i++) b[i] = abs(a[i] - a[i - 1]); long long int dp[n], dd[n]; dp[0] = 0; dd[0] = 0; for (int i = 1; i < n; i++) { if (i % 2 == 1) { dp[i] = dp[i - 1] + b[i]; dd[i] = max(dd[i - 1] - b[i], 0LL); } else { dp[i] = max(0LL, dp[i - 1] - b[i]); dd[i] = dd[i - 1] + b[i]; } } long long int ans = 0; for (int i = 0; i < n; i++) ans = max(ans, dp[i]); for (int i = 0; i < n; i++) ans = max(ans, dd[i]); cout << ans << endl; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const long long maxn = 5e5; long long n, a[maxn], b[maxn], res = 0, Maxn = 0; int main() { cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; } for (int i = 1; i < n; i++) { b[i] = abs(a[i] - a[i + 1]); } for (int i = 1; i < n; i++) { if (i % 2 == 0) { res += b[i]; } else { res -= b[i]; } Maxn = max(Maxn, res); res = max(res, 0ll); } res = 0; for (int i = 1; i < n; i++) { if (i % 2 == 1) { res += b[i]; } else { res -= b[i]; } Maxn = max(res, Maxn); res = max(res, 0ll); } cout << Maxn; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.util.StringTokenizer; public class cfs407C { public static void main(String[] args) { FastScanner sc = new FastScanner(); int N = sc.nextInt(); long[] arr = new long[N]; for (int n = 0; n < N; n++) { arr[n] = sc.nextLong(); } long[] diff = new long[N-1]; for (int n = 0; n < N-1; n++) { diff[n] = Math.abs(arr[n] - arr[n+1]); } System.out.println(Math.max(maxSub(diff, 0), maxSub(diff, 1))); } public static long maxSub(long[] arr, int m) { long maxEndHere = 0; long maxSoFar = 0; for (int i = m; i < arr.length; i+=2) { maxEndHere = Math.max(0, maxEndHere + arr[i]); maxSoFar = Math.max(maxSoFar, maxEndHere); if (i + 1 < arr.length) maxEndHere = Math.max(0, maxEndHere - arr[i+1]); } return maxSoFar; } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(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 readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
n = int(raw_input()) a = map(int,raw_input().split()) for i in range(n-1): a[i] = abs(a[i]-a[i+1]) dpplus = [0]*(n-1) dppminus = [0]*(n-1) dpplus[0],dppminus[0] = a[0],-a[0] for i in range(1,n-1): dpplus[i]=max(a[i],dppminus[i-1]+a[i]) dppminus[i] = max(-a[i],dpplus[i-1]-a[i]) print max(max(dpplus),max(dppminus))
PYTHON
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const int MAXN = 200005; int n; long long dp[MAXN]; long long a[MAXN]; long long Cal(int i) { return abs(a[i] - a[i + 1]); } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%I64d", &a[i]); dp[n - 1] = Cal(n - 1); long long ans = dp[n - 1]; for (int i = n - 2; i > 0; i--) { dp[i] = Cal(i); if (i < n - 2) dp[i] = max(dp[i], dp[i + 2] - Cal(i + 1) + Cal(i)); ans = max(dp[i], ans); } printf("%I64d\n", ans); }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int a[100100]; int b[100100]; int main() { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", a + i); } for (int i = 1; i < n; i++) { b[i] = abs(a[i] - a[i + 1]); } long long sum = 0, summ = 0; long long ans = -1; for (int i = 1; i < n; i++) { int temp = b[i]; if (i % 2 == 0) temp = -temp; summ += temp; sum += temp; ans = max(ans, sum); ans = max(ans, -summ); if (sum < 0) sum = 0; if (summ > 0) summ = 0; } cout << ans << endl; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
from sys import stdin, stdout n = int(stdin.readline().rstrip()) a = [int(q) for q in stdin.readline().rstrip().split()] fOdd = [] fEven = [] for i in range(n-1): fOdd.append(abs(a[i]-a[i+1])*(-1)**(i)) fEven.append(abs(a[i]-a[i+1])*(-1)**(i-1)) index=0 fOddCurrent=0 fEvenCurrent=0 fMax=0 while index<n-1: fOddCurrent+=fOdd[index] fEvenCurrent+=fEven[index] if index==0 or fEvenCurrent<0: fEvenCurrent=0 if fOddCurrent<0: fOddCurrent=0 fMax=max([fMax,fEvenCurrent,fOddCurrent]) index+=1 print(fMax)
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; int a[N], s[N]; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &a[i]); for (int i = 0; i < n - 1; i++) s[i] = abs(a[i] - a[i + 1]); long long maxs = 0; long long sum = 0; for (int i = 0; i < n - 1; i++) { if (sum < 0) sum = 0; sum += ((i % 2) ? 1 : -1) * s[i]; maxs = max(maxs, sum); } sum = 0; for (int i = 0; i < n - 1; i++) { if (sum < 0) sum = 0; sum += ((i % 2) ? -1 : 1) * s[i]; maxs = max(maxs, sum); } printf("%I64d\n", maxs); return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
# helper methods for input def ri(): return raw_input() def ii(type): x = ri() if type == 'i': return int(x) if type == 'l': return long(x) if type == 'f': return float(x) if type == 's': return str(x) return def i2(type): x = ri().split() if type == 'i': return int(x[0]), int(x[1]) if type == 'l': return long(x[0]), long(x[1]) if type == 'f': return float(x[0]), float(x[1]) if type == 's': return str(x[0]), str(x[1]) return def ni(type): array = ri().split() def doforall(x): if type == 'i': return int(x) if type == 'l': return long(x) if type == 'f': return float(x) if type == 's': return str(x) return array = map(doforall, array) return array def pr(array): def tostring(el): return str(el) print ' '.join(map(tostring, array)) def fndec(x): return '{0:.6f}'.format(x) # main n = ii('i') arr = ni('i') difarr = [] for i in range(0, n-1): difarr.append(abs(arr[i] - arr[i+1])) arr1 = difarr[0:] arr2 = difarr[1:] for i in range(1, len(arr1), 2): arr1[i] *= -1 for i in range(1, len(arr2), 2): arr2[i] *= -1 def maxsum(arr): ct = 0 ms = 0 for elem in arr: ct += elem if ct < 0: ct = 0 ms = max(ms, ct) return ms print max(maxsum(arr1), maxsum(arr2))
PYTHON
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Code { public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<arr.length;i++) { arr[i] = sc.nextInt(); } long[] a = new long[n-1]; a[0] = Math.abs(arr[0]-arr[1]); int k1 =1; int k2 = 2; for(int i=1;i<n-1;i++) a[i] = (long) (a[i-1] + Math.abs(arr[k1++]-arr[k2++])*Math.pow(-1, i)); //System.out.println(Arrays.toString(a)); int l = -1; int r = -1; long[] maxi = new long[n-1]; maxi[n-2] = a[n-2]; for(int i=n-3;i>=0;i--) { maxi[i] = (long)Math.max(maxi[i+1], a[i]); } //System.out.println(Arrays.toString(a)); // System.out.println(Arrays.toString(maxi)); long max = Long.MIN_VALUE; for(l=0;l<n-1;l++) { if(l==0) { max = Math.max(max, maxi[0]); }else { max = Math.max(max, maxi[0]-a[l]); //System.out.print(maxi[l]+" "); } } System.out.println(max); pw.flush(); pw.close(); } } class A1 implements Comparable<A1>{ long a;long b;long value; public A1(long f,long g) { a = f; b = g; value = a*b; } @Override public int compareTo(A1 o) { // TODO Auto-generated method stub if(value>o.value)return 1; if(value<o.value)return -1; return 0; } } class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } 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 { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.*; public class functions{ public static void main(String [] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n+1]; long ans = 0; for (int i = 1;i<=n ;i++ ) { a[i] = sc.nextInt(); } long[] b = new long[n+1]; long odd = 0; long even = 0; long s1 = 0; long s2 = 0; for (int i = 0;i < n ;i++ ) { b[i] = Math.abs(a[i]-a[i+1]); } for (int i = n-1;i >= 1; i--) { if (i%2 == 0) { even = even+b[i]; }else{ odd = odd+b[i]; } if (i%2 == 0) { ans = Math.max(ans,even-odd-s1); }else{ ans = Math.max(ans, odd-even-s2); } s1 = Math.min(s1,even-odd); s2 = Math.min(s2,odd-even); } System.out.println(ans); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int n, a[200005]; long long ans; long long solve() { long long Max = -99999999, Min = 0, sum[200005]; sum[0] = 0; for (int i = 1; i < n; i++) { sum[i] = sum[i - 1] + a[i]; Min = min(Min, sum[i]); Max = max(Max, sum[i] - Min); } return Max; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); for (int i = 1; i <= n - 1; i++) a[i] = abs(a[i + 1] - a[i]); for (int i = 1; i <= n - 1; i++) if (i % 2 == 0) a[i] /= -1; ans = -99999999; ans = max(ans, solve()); for (int i = 1; i <= n - 1; i++) a[i] *= -1; ans = max(ans, solve()); printf("%lld", ans); }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
n = int(raw_input()) A = map(int, raw_input().split()) def f(A): B = [] lenA = len(A) for i in range(lenA - 1): B += [abs(A[i] - A[i + 1]) * (-1) ** i] ll = len(B) #print B if ll < 1: return 0 l = 0 r = 0 curSum = B[0] maxSum = B[0] while l < ll and r < ll: while r < ll-1 and curSum >= 0: curSum += B[r + 1] maxSum = max(curSum, maxSum) r += 1 while l < r and curSum < 0: #print '(', l, '-', r, ') -- ', curSum curSum -= B[l] maxSum = max(curSum, maxSum) l += 1 if l < r: l += 1 curSum -= B[l] else: l += 1 r = l curSum = B[l] if l < len(B) else 0 return maxSum def main(A): return max(f(A), f(A[1:])) print main(A)
PYTHON
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; long long kadane(long long a[], long long s) { long long int maxx = 0, maxend = 0; for (long long int i = 0; i < s; i++) { maxend = maxend + a[i]; if (maxx < maxend) maxx = maxend; if (maxend < 0) maxend = 0; } return maxx; } int main() { long long int n; cin >> n; long long int i; long long int arr[n]; for (i = 0; i < n; i++) { cin >> arr[i]; } long long int f1[n - 1], f2[n - 1]; for (i = 0; i < n - 1; i++) { f1[i] = abs(arr[i] - arr[i + 1]); f2[i] = f1[i]; } for (i = 0; i < n - 1; i++) { if (i % 2 == 0) f1[i] *= -1; else f2[i] *= -1; } long long ans = max(kadane(f1, n - 1), kadane(f2, n - 1)); cout << ans << endl; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int a[100005]; long long s[100005], d[100005], d2[100005]; long long max(long long a, long long b) { if (a < b) return b; return a; } int abs(int x) { if (x > 0) return x; return -x; } int main() { int n, i; long long S, res = -1e9; scanf("%d", &n); for (i = 1; i <= n; i++) { scanf("%d", &a[i]); } for (i = 1; i < n; i++) { s[i] = abs(a[i] - a[i + 1]); } S = 0; for (i = n - 1; i >= 0; i--) { if (i % 2) S -= s[i]; else S += s[i]; if (S < 0) S = 0; d[i] = S; } S = 0; for (i = n - 1; i >= 0; i--) { if (i % 2) S += s[i]; else S -= s[i]; d2[i] = S; if (S < 0) S = 0; } for (i = n - 1; i >= 0; i--) { if (i % 2 == 0) res = max(res, d[i]); else res = max(res, d2[i]); } printf("%lld", res); return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.*; import java.math.BigInteger; import java.util.*; public class main { private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; private static long mod = 1000000000 + 7; private static void soln() { /*long b1= nextLong(); long q=nextLong(); long l =nextLong(); int m =nextInt(); HashSet<Long> set = new HashSet<>(); for(int i=0;i<m;i++) set.add(nextLong()); //int[] arr = nextIntArray(m); long b=Math.abs(b1); if(q==1) { if(set.contains(b1) || b>l) pw.println(0); else pw.println("inf"); } else if(q==-1) { if(b<=l) { if(!set.contains(b1) || !set.contains(-b1)) pw.println("inf"); else pw.println(0); }else pw.println(0); } else if(b1==0) { if(set.contains(0)) pw.println(0); else pw.println("inf"); }else if(q==0) { if(b<=l) { if(set.contains(0)) if(set.contains(b1)) pw.println(0); else pw.println(1); else pw.println("inf"); } else pw.println("0"); } else { int cnt=0; while(Math.abs(b1)<=l) { if(!set.contains(b1)) cnt++; b1*=q; } pw.println(cnt); }*/ int n = nextInt(); int[] arr = nextIntArray(n); long[] diff = new long[n-1]; for(int i=0;i<n-1;i++) diff[i]=Math.abs(arr[i]-arr[i+1]); TreeSet<Long> set = new TreeSet<>(); set.add(0L); long totdiff=0; long ans = 0; for(int i=0;i<n-1;i++) { long totdiff1 = 0; if(i%2==0) { totdiff+=diff[i]; totdiff1 = totdiff - set.first(); } else { totdiff-=diff[i]; totdiff1 = set.last() - totdiff; } //totdiff = Math.max(totdiff - set.first(), set.last() - totdiff); ans = Math.max(totdiff1, ans); set.add(totdiff); } pw.println(ans); } public static class Segment { private int[] tree; private boolean[] lazy; private int size; private int n; private class node{ private int a; private int b; private int c; public node(int x,int y,int z){ a=x; b=y; c=z; } } public Segment(int n){ //this.base=arr; int x = (int) (Math.ceil(Math.log(n) / Math.log(2))); size = 2 * (int) Math.pow(2, x) - 1; tree=new int[size]; lazy=new boolean[size]; this.n=n; build(0,0,n-1); } public void build(int id,int l,int r) { if(l==r) { return; } int mid=(l+r)/2; build(2*id+1,l,mid); build(2*id+2,mid+1,r); tree[id]=tree[2*id+1]+tree[2*id+2]; } public int query(int l,int r){ return queryUtil(l,r,0,0,n-1); } private int queryUtil(int x,int y,int id,int l,int r){ if(l>y || x>r) return 0; if(x <= l && r<=y) { //if(!lazy[id]) return tree[id]; //else // return tree[id][0]; } int mid=l+(r-l)/2; shift(id); return queryUtil(x,y,2*id+1,l,mid)+queryUtil(x,y,2*id+2,mid+1,r); } public void update(int x,int y,int colour,int id,int l,int r){ //System.out.println(l+" "+r+" "+x); if(x>r || y<l) return; if(x <= l && r<=y) { return; } int mid=l+(r-l)/2; shift(id); update(x,y,colour,2*id+1,l,mid); update(x,y,colour,2*id+2,mid+1,r); tree[id]=tree[2*id+1]+tree[2*id+2]; } public void shift(int id) { } } public static void fft(double[] a, double[] b, boolean invert) { int count = a.length; for (int i = 1, j = 0; i < count; i++) { int bit = count >> 1; for (; j >= bit; bit >>= 1) j -= bit; j += bit; if (i < j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; temp = b[i]; b[i] = b[j]; b[j] = temp; } } for (int len = 2; len <= count; len <<= 1) { int halfLen = len >> 1; double angle = 2 * Math.PI / len; if (invert) angle = -angle; double wLenA = Math.cos(angle), wLenB = Math.sin(angle); for (int i = 0; i < count; i += len) { double wA = 1, wB = 0; for (int j = 0; j < halfLen; j++) { double uA = a[i + j], uB = b[i + j]; double vA = a[i + j + halfLen] * wA - b[i + j + halfLen] * wB; double vB = a[i + j + halfLen] * wB + b[i + j + halfLen] * wA; a[i + j] = uA + vA; b[i + j] = uB + vB; a[i + j + halfLen] = uA - vA; b[i + j + halfLen] = uB - vB; double nextWA = wA * wLenA - wB * wLenB; wB = wA * wLenB + wB * wLenA; wA = nextWA; } } } if (invert) { for (int i = 0; i < count; i++) { a[i] /= count; b[i] /= count; } } } static void multiply(long[][] a, long[][] b, long m) { int n = a.length; long[][] mul = new long[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { mul[i][j] = 0; for (int k = 0; k < n; k++) mul[i][j] = (mul[i][j] + (a[i][k] * b[k][j]) % m) % m; } } for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i][j] = mul[i][j]; } private static long pow(long a, long b, long c) { if (b == 0) return 1; long p = pow(a, b / 2, c); p = (p * p) % c; return (b % 2 == 0) ? p : (a * p) % c; } private static long gcd(long n, long l) { if (l == 0) return n; return gcd(l, n % l); } public static void main(String[] args) throws Exception { // new Thread(null, new Runnable() // { // @Override // public void run() // { // /*try { // InputReader(new FileInputStream("C:\\Users\\hardik\\Desktop\\B-large-practice.in")); // } catch (FileNotFoundException e) { // TODO Auto-generated catch block // e.printStackTrace(); // } */ // InputReader(System.in); // pw = new PrintWriter(System.out); // /*try { // pw=new PrintWriter(new FileOutputStream("C:\\Users\\hardik\\Desktop\\out.txt")); // } catch (FileNotFoundException e) { // TODO Auto-generated catch block // e.printStackTrace(); // }*/ // soln(); // pw.close(); // } // }, "1", 1 << 26).start(); /*try { InputReader(new FileInputStream("C:\\Users\\hardik\\Desktop\\B-large-practice.in")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ InputReader(System.in); pw = new PrintWriter(System.out); /*try { pw=new PrintWriter(new FileOutputStream("C:\\Users\\hardik\\Desktop\\out.txt")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ soln(); pw.close(); } public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static 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++]; } private static 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; } private static 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; } private static String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private static 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(); } private static int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } private static long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private static void pArray(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); return; } private static void pArray(long[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); return; } private static boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private static char nextChar() { int c = read(); while (isSpaceChar(c)) c = read(); char c1 = (char) c; while (!isSpaceChar(c)) c = read(); return c1; } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.*; public class TestClass { static long f(long dp[],int n){ long fm=dp[0],tm=dp[0]; for(int i=1;i<n;i++){ tm=Math.max(tm+dp[i],dp[i]); fm=Math.max(fm,tm); } return fm; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++){ a[i]=sc.nextInt(); } long dp1[]=new long[n-1]; long dp2[]=new long[n-1]; int f1=1,f2=-1; for(int i=1;i<n;i++){ long temp=Math.abs(a[i]-a[i-1]); dp1[i-1]=f1*temp; dp2[i-1]=f2*temp; f1*=-1; f2*=-1; } System.out.println(Math.max(f(dp1,n-1),f(dp2,n-1))); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.*; import java.io.*; public class Hello { public static void main(String[] args) { FastReader s=new FastReader(); PrintWriter pr=new PrintWriter(System.out,true); int n=s.nextInt(); int a[]=new int[n+1]; for(int i=1;i<=n;i++) a[i]=s.nextInt(); long max=Long.MIN_VALUE; boolean toggle; for(int i=1;i<=2;i++){ int dp[]=new int[n+1]; toggle=false; for(int j=i+1;j<=n;j++){ if(i+1==j){ dp[j]=Math.abs(a[j-1]-a[j]); toggle=true; } else{ if(toggle){ dp[j]=Math.abs(a[j-1]-a[j])*(-1); toggle=false; } else{ dp[j]=Math.abs(a[j-1]-a[j]); toggle=true; } } } max=Math.max(max,fun(dp)); } pr.println(max); pr.close(); } public static long fun(int a[]){ int n=a.length; long ans=Long.MIN_VALUE; long sum=0; for(int i=1;i<n;i++){ //System.out.print(a[i]+" "); if(sum+a[i]>=0){ sum+=a[i]; } else{ sum=0; } ans=Math.max(ans,sum); } //System.out.println(); return ans; } } 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
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; long long st[100005]; bool binSearch(long long beg, long long end, long long num) { if (beg == end) { if (st[beg] == num) return true; else return false; } if (binSearch(beg, (beg + end) / 2, num)) return true; else if (binSearch((beg + end) / 2 + 1, end, num)) return true; else return false; } int main() { long long n; cin >> n; long long st2[100005]; long long sumarr[100005]; long long sumend[100005]; long long sum = 0, ans = 0; long long summin2 = 0; for (int i = 0; i < n; i++) { cin >> st[i]; } for (int i = 0; i < n - 1; i++) { if (i % 2 == 0) st2[i] = abs(st[i] - st[i + 1]); else st2[i] = -abs(st[i] - st[i + 1]); } sum = 0; for (int r = 0; r < n - 1; ++r) { summin2 += st2[r]; sum = max(sum, summin2); summin2 = max(summin2, (long long)0); } ans = sum; for (int i = 0; i < n - 1; i++) { if (i % 2 == 0) st2[i] = -abs(st[i] - st[i + 1]); else st2[i] = abs(st[i] - st[i + 1]); } sum = 0; summin2 = 0; for (int r = 0; r < n - 1; ++r) { summin2 += st2[r]; sum = max(sum, summin2); summin2 = max(summin2, (long long)0); } ans = max(ans, sum); cout << ans; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.util.*; public class Main { static long mod = 998244353; static int size = 200000; static long[] fac = new long[size]; static long[] finv = new long[size]; static long[] inv = new long[size]; static int INF = Integer.MAX_VALUE; public static void main(String[] args){ Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] a = new int[n+1]; int[] b = new int[n]; for(int i = 0; i < n ; i++){ a[i] = scanner.nextInt(); } for(int i = 0; i < n; i++){ if(i % 2 == 0){ b[i] = Math.abs(a[i]-a[i+1]); }else{ b[i] = Math.abs(a[i]-a[i+1])*(-1); } } long[] sum = new long[n]; for(int i = 0; i < n-1; i++){ sum[i+1] = sum[i] + b[i]; } long[] min = new long[n]; for(int i = 0; i < n; i++){ min[i] = Long.MAX_VALUE; } min[0] = 0; long ans = Long.MIN_VALUE; for(int i = 1; i < n; i++){ min[i] = Math.min(min[i-1],sum[i]); } long[] max = new long[n]; for(int i = 0; i < n; i++){ max[i] = Long.MIN_VALUE; } max[0] = 0; for(int i = 1; i < n; i++){ max[i] = Math.max(max[i-1],sum[i]); } for(int i = 0; i < n; i++){ ans = Math.max(ans,sum[i]-min[i]); ans = Math.max(ans,max[i]-sum[i]); } System.out.println(ans); //for(int i = 0; i < n; i++){ //System.out.println(sum[i]); //} } public static boolean isPrime(int n){ if(n == 1) return false; if(n == 2 || n == 3) return true; for(int i = 2; i <= Math.sqrt(n); i++){ if(n % i == 0) return false; } return true; } // tar の方が数字が大きいかどうか static boolean compare(String tar, String src) { if (src == null) return true; if (src.length() == tar.length()) { int len = tar.length(); for (int i = 0; i < len; i++) { if (src.charAt(i) > tar.charAt(i)) { return false; } else if (src.charAt(i) < tar.charAt(i)) { return true; } } return tar.compareTo(src) > 0 ? true : false; } else if (src.length() < tar.length()) { return true; } else if (src.length() > tar.length()) { return false; } return false; } public static class Edge{ int from; int to; Edge(int from, int to){ this.from = from; this.to = to; } } public static void swap(long a, long b){ long tmp = 0; if(a > b){ tmp = a; a = b; b = tmp; } } static class Pair implements Comparable<Pair>{ int first, second; Pair(int a, int b){ first = a; second = b; } @Override public boolean equals(Object o){ if (this == o) return true; if (!(o instanceof Pair)) return false; Pair p = (Pair) o; return first == p.first && second == p.second; } @Override public int compareTo(Pair p){ return first == p.first ? second - p.second : first - p.first; //firstで昇順にソート //return (first == p.first ? second - p.second : first - p.first) * -1; //firstで降順にソート //return second == p.second ? first - p.first : second - p.second;//secondで昇順にソート //return (second == p.second ? first - p.first : second - p.second)*-1;//secondで降順にソート } } //繰り返し二乗法 public static long pow(long x, long n){ long ans = 1; while(n > 0){ if((n & 1) == 1){ ans = ans * x; ans %= mod; } x = x * x % mod; n >>= 1; } return ans; } public static long div(long x, long y){ return (x*pow(y, mod-2))%mod; } //fac, inv, finvテーブルの初期化、これ使う場合はinitComb()で初期化必要 public static void initComb(){ fac[0] = finv[0] = inv[0] = fac[1] = finv[1] = inv[1] = 1; for (int i = 2; i < size; ++i) { fac[i] = fac[i - 1] * i % mod; inv[i] = mod - (mod / i) * inv[(int) (mod % i)] % mod; finv[i] = finv[i - 1] * inv[i] % mod; } } //nCk % mod public static long comb(int n, int k){ return fac[n] * finv[k] % mod * finv[n - k] % mod; } //n! % mod public static long fact(int n){ return fac[n]; } //(n!)^-1 with % mod public static long finv(int n){ return finv[n]; } static class UnionFind { int[] parent; public UnionFind(int size) { parent = new int[size]; Arrays.fill(parent, -1); } public boolean unite(int x, int y) { x = root(x); y = root(y); if (x != y) { if (parent[y] < parent[x]) { int tmp = y; y = x; x = tmp; } parent[x] += parent[y]; parent[y] = x; return true; } return false; } public boolean same(int x, int y) { return root(x) == root(y); } public int root(int x) { return parent[x] < 0 ? x : (parent[x] = root(parent[x])); } public int size(int x) { return -parent[root(x)]; } } public static int upperBound(int[] array, int value) { int low = 0; int high = array.length; int mid; while( low < high ) { mid = ((high - low) >>> 1) + low; // (high + low) / 2 if( array[mid] <= value ) { low = mid + 1; } else { high = mid; } } return low; } public static final int lowerBound(final int[] arr, final int value) { int low = 0; int high = arr.length; int mid; while (low < high){ mid = ((high - low) >>> 1) + low; //(low + high) / 2 (オーバーフロー対策) if (arr[mid] < value) { low = mid + 1; } else { high = mid; } } return low; } //n,mの最大公約数 public static long gcd(long n, long m){ if(m > n) return gcd(m,n); if(m == 0) return n; return gcd(m, n%m); } //3要素のソート private class Pair2 implements Comparable<Pair2> { String s; int p; int index; public Pair2(String s, int p, int index) { this.s = s; this.p = p; this.index = index; } public int compareTo(Pair2 other) { if (s.equals(other.s)) { return other.p - this.p; } return this.s.compareTo(other.s); } } //c -> intに変換 public static int c2i(char c){ if('A' <= c && c <= 'Z'){ return c - 'A'; }else{ return c - 'a' + 26; } } // int -> charに変換 public static char i2c(int i){ if(0 <= i && i < 26){ return (char)(i + 'A'); }else{ return (char)(i + 'a' - 26); } } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; long long A[1000005]; int main() { int n; cin >> n; for (int i = 1; i <= n; ++i) scanf("%I64d", &A[i]); long long ma = abs(A[n - 1] - A[n]); long long mi = ma; long long lma = ma; long long lmi = mi; for (int i = n - 2; i > 0; --i) { long long temp1 = abs(A[i] - A[i + 1]) - lma; long long temp2 = abs(A[i] - A[i + 1]) - lmi; ma = max(ma, max(temp1, temp2)); mi = min(mi, min(temp1, temp2)); ma = max(abs(A[i] - A[i + 1]), ma); mi = min(mi, abs(A[i] - A[i + 1])); lma = max(abs(A[i] - A[i + 1]), max(temp1, temp2)); lmi = min(min(temp1, temp2), abs(A[i] - A[i + 1])); } cout << ma << endl; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.*; import java.util.*; import java.text.*; public class Main { private static long kadane(long input[]){ long curMax=input[0]; long max=input[0]; for(int i=1;i<input.length;i++){ curMax=Math.max(input[i],curMax+input[i]); max=Math.max(max,curMax); } return max; } public static void main (String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String st[] = br.readLine().split(" "); int n=Integer.parseInt(st[0]); st=br.readLine().split(" "); long input[]=new long[n]; for(int i=0;i<n;i++){ input[i]=Long.parseLong(st[i]); } long a[]=new long[n-1]; long b[]=new long[n-1]; for(int i=0;i<n-1;i++){ a[i]=Math.abs(input[i]-input[i+1]); if(i%2==1){ a[i]=-a[i]; } b[i]=-a[i]; } System.out.println(Math.max(kadane(a),kadane(b))); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.*; import java.util.StringTokenizer; /** * Created by Julia on 01.04.2017. */ public class SolverC { public static void main(String[] args) throws IOException { new SolverC().run(); } StringTokenizer stok; BufferedReader br; PrintWriter pw; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { stok = new StringTokenizer(br.readLine()); } return stok.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } void run() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new OutputStreamWriter(System.out)); // br = new BufferedReader(new FileReader("input.txt")); // pw = new PrintWriter("output.txt"); solve(); pw.close(); } private void solve() throws IOException { int n = nextInt(); long[] mas = new long[n]; for (int i=0; i<n; i++) { mas[i]=nextInt(); } long[] newmas = new long[n-1]; int mn=1; for (int i=0; i<n-1; i++){ newmas[i]=Math.abs(mas[i]-mas[i+1])*mn; mn=-mn; } long result=0; long cur=0; for (int i=0; i<n-1; i++) { cur+=newmas[i]; if (cur<0) { cur=0; } result = Math.max(result, cur); } cur=0; for (int i=0; i<n-1; i++) { cur-=newmas[i]; if (cur<0) { cur=0; } result = Math.max(result, cur); } pw.println(result); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import sys from io import BytesIO, IOBase import os BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") n=int(input()) a=list(map(int,input().split())) if n==2: print(abs(a[0]-a[1])) exit() mx_cur1,mx_glob1=abs(a[0]-a[1]),abs(a[0]-a[1]) for i in range(1,n-1): tmp=abs(a[i]-a[i+1])*(-1)**i mx_cur1=max(mx_cur1+tmp,tmp) mx_glob1=max(mx_cur1,mx_glob1) mx_cur2,mx_glob2=abs(a[1]-a[2]),abs(a[1]-a[2]) for i in range(2,n-1): tmp=abs(a[i]-a[i+1])*(-1)**(i-1) mx_cur2=max(mx_cur2+tmp,tmp) mx_glob2=max(mx_glob2,mx_cur2) print(max(mx_glob1,mx_glob2))
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; 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); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { int[] arr; int[] sarr; long temp; int n; private void getIt(int res) { long x = 0; for (int i = res; i <= n; i++) { if ((i - res) % 2 == 0) { x += sarr[i]; } else { x -= sarr[i]; } temp = Math.max(temp, x); if (x < 0) x = 0; } } public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); this.temp = 0; int cur = 0; int res = 0; arr = new int[(int) 2e5]; sarr = new int[(int) 2e5]; for (int i = 1; i <= n; i++) { arr[i] = in.nextInt(); if (i > 1) { sarr[++cur] = Math.abs(arr[i] - arr[i - 1]); } } getIt(1); getIt(2); out.println(temp); } } 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()); } } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
n = int(input()) arr = list(map(int, input().split())) diff = [abs(arr[i] - arr[i-1]) for i in range(1, n)] res0, res1, res, curr_sum = -2e9, 0, -2e9, 0 for i in range(n-1): curr_sum += diff[i] * (1 if i % 2 == 0 else -1) res = max(res, curr_sum - res1, res0 - curr_sum) if i % 2 == 0: res0 = max(res0, curr_sum) else: res1 = min(res1, curr_sum) print(res)
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.*; import java.lang.reflect.Array; import java.util.*; /** * Created by Alexander on 18.03.2017. */ public class Stress { BufferedReader br; StringTokenizer sc; PrintWriter out; public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); new Stress().run(); } void run() throws IOException { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // br = new BufferedReader(new FileReader("trains.in")); // out = new PrintWriter(new File("trains.out")); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } String nextToken() throws IOException { while (sc == null || !sc.hasMoreTokens()) { try { sc = new StringTokenizer(br.readLine()); } catch (Exception e) { return null; } } return sc.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } class Edge implements Comparable<Edge> { int v, u, w, num; public Edge(int v, int u, int w, int num) { this.v = v; this.u = u; this.w = w; this.num = num; } @Override public int compareTo(Edge o) { return Integer.compare(w, o.w); } } class Pair { int id; int d; Pair(int a, int b) { id = a; d = b; } } ArrayList<Edge> g[]; void solve() throws IOException { int n = nextInt(); int a[] = new int[n]; long suf[] = new long[n]; long max = Long.MIN_VALUE; int cnt1 = 0; for (int i = 0; i < n; i++) { a[i] = nextInt(); } for (int i = n - 2; i >= 0; i--) { suf[i] = (-1) * suf[i + 1] + Math.abs(a[i] - a[i + 1]); if (suf[i] > max) { max = suf[i]; cnt1 = i; } } long min = Long.MAX_VALUE; int cnt2 = 0; for(int i = n - 1; i >= 0; i--){ if(i % 2 == cnt1 % 2){ if(min > suf[i]){ min = suf[i]; cnt2 = i; } }else{ if(min > (-1)*suf[i]){ min = (-1)*suf[i]; cnt2 = i; } } } out.println(max - min); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const int MX = 1e5 + 5; long long a[MX], dp[MX][2]; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; for (int i = 1; i < n; i++) { a[i] = abs(a[i] - a[i + 1]); } dp[1][1] = a[1]; dp[1][0] = 0; long long ans = a[1]; for (int i = 2; i < n; i++) { if (i % 2) { dp[i][0] = dp[i - 1][0] - a[i]; dp[i][1] = max(a[i], dp[i - 1][1] + a[i]); ans = max(ans, max(dp[i][0], dp[i][1])); } else { dp[i][0] = max(a[i], dp[i - 1][0] + a[i]); dp[i][1] = dp[i - 1][1] - a[i]; ans = max(ans, max(dp[i][0], dp[i][1])); } } cout << ans; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; long long int dp[100005]; int n; long long int findmax() { long long int max_sum = 0; long long int mini = INT_MIN; for (int i = 0; i < n - 1; i++) { max_sum += dp[i]; if (max_sum > mini) mini = max_sum; if (max_sum < 0) max_sum = 0; } return mini; } int main() { memset(dp, 0, sizeof(dp)); cin >> n; long long int a[n + 5]; for (int i = 0; i < n; i++) { cin >> a[i]; } for (int i = 0; i < n - 1; i++) { dp[i] = abs(a[i] - a[i + 1]); if (i % 2 != 0) dp[i] = -1ll * dp[i]; } long long int sum1 = findmax(); for (int i = 0; i < n - 1; i++) dp[i] = -1 * dp[i]; long long int sum2 = findmax(); cout << max(sum1, sum2); return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
# by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase def kadane(lst): su,ans = 0,0 for i in lst: su = max(0,su+i) ans = max(ans,su) return ans def main(): n = int(input()) a = list(map(int,input().split())) ls = [pow(-1,i)*abs(a[i+1]-a[i]) for i in range(n-1)] ls1 = [-1*ls[i] for i in range(1,len(ls))] print(max(kadane(ls),kadane(ls1))) #Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == '__main__': main()
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
//package a2oj_dp; import java.io.*; import java.util.Arrays; public class Functions_again { public static void main(String[] args) throws IOException{ InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); int n = Integer.parseInt(br.readLine()); int[] arr = new int[n]; String[] s = br.readLine().split(" "); for(int i = 0; i < n-1; i++) { arr[i] = Math.abs(Integer.parseInt(s[i]) - Integer.parseInt(s[i+1])); } long[] dp = new long[n+1]; long max = 0; for(int i = n-2; i >= 0 ; i--) { dp[i] = arr[i] + Math.max(0, dp[i+2] - arr[i+1]); max = Math.max(dp[i], max); } // System.out.println(Arrays.toString(arr)); // System.out.println(Arrays.toString(dp)); System.out.println(max); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
def max_subarray(numbers,k): best_sum = 0 current_sum = 0 for x in range(len(numbers)): if(k%2==k): current_sum = max(0, current_sum + numbers[x]) else: current_sum = current_sum + numbers[x] best_sum = max(best_sum, current_sum) return best_sum n = int(input()) l = list(map(int,input().split())) l1 = [] l2 = [] s = 1 for i in range(n-1): l1.append(abs(l[i]-l[i+1])*(s)) l2.append(abs(l[i] - l[i + 1]) * (-1 *s)) s = s*-1 print(max(max_subarray(l1,0),max_subarray(l2,1)))
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
n = int(raw_input()) a = map(int, raw_input().split()) b = [] c = [] for i in range(n-1): val = abs(a[i+1]-a[i]) if(i%2==1): val*=-1 b.append(val) for i in range(n-1): val = abs(a[i+1]-a[i]) if((i+1)%2==1): val*=-1 c.append(val) c_pref = [c[0]] b_pref = [b[0]] for i in range(1,n-1): c_pref.append(max(c[i],c_pref[i-1]+c[i])) b_pref.append(max(b[i],b_pref[i-1]+b[i])) print max(max(c_pref),max(b_pref))
PYTHON
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; long long dp[100010], arr[100010]; int main() { long long n, x, i, mx, y; cin >> n; cin >> x; for (i = 2; i <= n; i++) { cin >> y; arr[i - 1] = abs(x - y); x = y; } n--; if (n == 1) { cout << arr[1] << endl; return 0; } dp[1] = arr[1]; dp[2] = arr[2]; for (i = 3; i <= n; i++) { dp[i] = max(arr[i], arr[i] - arr[i - 1] + dp[i - 2]); } mx = 0; for (i = 1; i <= n; i++) { mx = max(mx, dp[i]); } cout << mx << endl; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; 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); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); long[] a = new long[N]; for (int i = 0; i < N; i += 1) { a[i] = in.nextInt(); } long ans = Math.abs(a[1] - a[0]); long plus = 0; long minus = ans; for (int i = 2; i < N; i += 1) { long diff = Math.abs(a[i - 1] - a[i]); minus = Math.max(0, minus - diff); plus += diff; ans = Math.max(ans, plus); ans = Math.max(ans, minus); long tmp = plus; plus = minus; minus = tmp; } out.println(ans); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); 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()); } } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
def maxSubArraySum(a, size): max_so_far = -9999999999999 - 1 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] if (max_so_far < max_ending_here): max_so_far = max_ending_here if max_ending_here < 0: max_ending_here = 0 return max_so_far a = int(input()) b = list(map(int,input().split())) dp = [] for x in range(1,a): dp.append(abs(b[x]-b[x-1])) dp1 = dp.copy() for x in range(a-1): if x%2 != 0: dp[x] = -dp[x] for x in range(1,a-1): if x%2 == 0: dp1[x] = -dp1[x] j = maxSubArraySum(dp,a-1) h = maxSubArraySum(dp1[1:],a-2) print(max(j,h))
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import sys input=sys.stdin.readline n=int(input()) l=input().split() li=[int(i) for i in l] l=[] for i in range(1,n): l.append(abs(li[i]-li[i-1])*pow(-1,i)) dp=[0 for i in range(n-1)] dp[0]=l[0] for i in range(1,n-1): dp[i]=max(l[i],l[i]+dp[i-1]) maxa=0 for i in dp: maxa=max(maxa,i) for i in range(n-1): l[i]=-l[i] dp=[0 for i in range(n-1)] dp[0]=l[0] for i in range(1,n-1): dp[i]=max(l[i],l[i]+dp[i-1]) for i in dp: maxa=max(maxa,i) print(maxa)
PYTHON3
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.awt.List; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; 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; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Queue; import java.util.Scanner; import java.util.Set; import java.util.Stack; import java.util.*; public class cool { private static InputStream stream; private static PrintWriter pw; // static int a; // static int b; // static int f = 0; static int n; static int m; // static int[][] arr; //static char[][] arr; static int Arr[]; static int tree[]; static int time = 0; static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}}; static int visited[]; static int visited2[][]; static Stack<Integer> stack; // static ArrayList<Integer> ans; // static int arr[][]; // static int arr[]; static char[][] arr; static char[][] ans; // static int[][] visited; // static int c; // static int d[]; // static int arr[][]; static ArrayList[] adj; // static ArrayList<Integer> ans; // static int f; static int parent[]; static int color[]; // static ArrayList<Integer> comp[]; static int f = 0; static int k = 0; static int count = 0; static int ini[]; static ArrayList<Node> list; static ArrayList<Integer> ind; public static void main(String[] args){ //InputReader(System.in); pw = new PrintWriter(System.out); Scanner in = new Scanner(System.in); int n = in.nextInt(); in.nextLine(); int arr[] = new int[n-1]; int a = in.nextInt(); for(int i = 0;i<n-1;i++){ int c = in.nextInt(); arr[i] = Math.abs(a-c); a = c; //pw.println(arr[i]); } long dp[][] = new long[2][n]; long max = 0; for(int i = 1;i<n;i++){ dp[0][i] = Math.max(arr[i-1], dp[1][i-1]+arr[i-1]); dp[1][i] = Math.max(0, dp[0][i-1]-arr[i-1]); max = Math.max(max, Math.max(dp[0][i], dp[1][i])); } pw.println(max); pw.close(); } public static void dfs(int i,int c){ if(visited[i] == 1){ return; } visited[i] = 1; for(int j = 0;j<adj[i].size();j++){ if(color[(int)adj[i].get(j)] == c){ dfs((int)adj[i].get(j),c); }else{ count++; } } } public static long pow(long n,long p,long m){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } public static int cs(ArrayList<Integer> arr, int low, int high, int x) { int mid; if(x <= arr.get(low)) return low; if(x > arr.get(high)) return -1; mid = (low + high)/2; if(arr.get(mid) == x) return mid; else if(arr.get(mid) < x) { if(mid + 1 <= high && x <= arr.get(mid+1)) return mid + 1; else return cs(arr, mid+1, high, x); } else { if(mid - 1 >= low && x > arr.get(mid-1)) return mid; else return cs(arr, low, mid - 1, x); } } public static int fs(ArrayList<Integer> arr, int low, int high, int x) { if (low > high) return -1; if (x >= arr.get(high)) return high; // Find the middle point int mid = (low+high)/2; // If middle point is floor. if (arr.get(mid) == x) return mid; // If x lies between mid-1 and mid if (mid > 0 && arr.get(mid-1) <= x && x < arr.get(mid)) return mid-1; // If x is smaller than mid, floor must be in // left half. if (x < arr.get(mid)) return fs(arr, low, mid-1, x); // If mid-1 is not floor and x is greater than // arr[mid], return fs(arr, mid+1, high, x); } public static long gcd(long x, long y) { if (x == 0) return y; else return gcd( y % x,x); } // public static void dfs(int a,int p){ // System.out.println(a); // if(a > 30000){ // return; // } // // if(visited[a] == 1){ // return; // } // // visited[a] = 1; // // if(ini[a] != 0){ // count+= ini[a]; // } // // int l = a-p; // // if(visited[a+l-1] == 0){ // dfs(a+l-1,a); // }else if(visited[a+l] == 0){ // dfs(a+l,a); // }else if(visited[a+l+1] == 0){ // dfs(a+l+1,a); // } // // } // public static int prev(int i,boolean[] arr){ while(arr[i]){ if(i == 0){ if(arr[i]){ return -1; }else{ return 0; } } i--; } return i; } public static int next(int i,boolean[] arr){ while(arr[i]){ if(i == arr.length-1){ if(arr[i]){ return -1; }else{ return 0; } } i++; } return i; } private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap) { // 1. Convert Map to List of Map LinkedList<Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet()); // 2. Sort list with Collections.sort(), provide a custom Comparator // Try switch the o1 o2 position for a different order Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // 3. Loop the sorted list and put it into a new insertion order Map LinkedHashMap Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> entry : list) { sortedMap.put(entry.getKey(), entry.getValue()); } /* //classic iterator example for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext(); ) { Map.Entry<String, Integer> entry = it.next(); sortedMap.put(entry.getKey(), entry.getValue()); }*/ return sortedMap; } public static ArrayList<Integer> Range(int[] numbers, int target) { int low = 0, high = numbers.length - 1; // get the start index of target number int startIndex = -1; while (low <= high) { int mid = (high - low) / 2 + low; if (numbers[mid] > target) { high = mid - 1; } else if (numbers[mid] == target) { startIndex = mid; high = mid - 1; } else low = mid + 1; } // get the end index of target number int endIndex = -1; low = 0; high = numbers.length - 1; while (low <= high) { int mid = (high - low) / 2 + low; if (numbers[mid] > target) { high = mid - 1; } else if (numbers[mid] == target) { endIndex = mid; low = mid + 1; } else low = mid + 1; } ArrayList<Integer> list = new ArrayList<Integer>(); int c = 0; if (startIndex != -1 && endIndex != -1){ for(int i = startIndex;i<=endIndex;i++){ list.add(i); } } return list; } private static int root(int Arr[],int i) { while(Arr[ i ] != i) //chase parent of current element until it reaches root { Arr[ i ] = Arr[ Arr[ i ] ] ; i = Arr[ i ]; } return i; } private static void union(int Arr[],int size[],int A,int B) { int root_A = root(Arr,A); int root_B = root(Arr,B); System.out.println(root_A + " " + root_B); if(root_A != root_B){ if(size[root_A] < size[root_B ]) { Arr[ root_A ] = Arr[root_B]; size[root_B] += size[root_A]; } else { Arr[ root_B ] = Arr[root_A]; size[root_A] += size[root_B]; } } } private static boolean find(int A,int B) { if( root(Arr,A)==root(Arr,B) ) //if A and B have the same root, it means that they are connected. return true; else return false; } // // public static void bfs(int i){ // // Queue<Integer> q=new LinkedList<Integer>(); // q.add(i); // // visited[i] = 1; // c++; // nodes++; // while(!q.isEmpty()){ // int top=q.poll(); // // Iterator<Integer> it= arr[top].listIterator(); // while(it.hasNext()){ // int next =it.next(); // // if(visited[next] == 0){ // nodes++; // visited[next] = 1; // q.add(next); // } // // } // } // // } // public static void dfs(int i){ // // // if(visited[i] == 1){ // return; // } // // visited[i] = 1; // con[c].add(i); // //System.out.print(i + " "); // for(int j = 0;j<arr[i].size();j++){ // dfs(arr[i].get(j)); // } // // } // // // public static void dfss(int i){ // if(visited[i] == 1){ // return; // } // // visited[i] = 1; // // for(int j = 0;j<arr[i].size();j++){ // dfss(arr[i].get(j)); // } // // System.out.println(i); // stack.push(i); // } // // public static void reverse(){ // ArrayList[] temp = new ArrayList[n]; // // for(int i = 0;i<n;i++){ // temp[i] = new ArrayList(); // } // // for(int i = 0;i<n;i++){ // for(int j = 0;j<arr[i].size();j++){ // temp[arr[i].get(j)].add(i); // } // } // // arr = temp; // // } // // public static boolean isPrime(int 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; } // union code starts // union code ends // // Segment tree code begins // // // static void build(int node,int start,int end) // { // if(start==end) // tree[node]=a[start]; // else // { // int mid=(start+end)/2; // build(2*node,start,mid); // build(2*node+1,mid+1,end); // if(tree[2*node]<tree[2*node+1]) // tree[node]=tree[2*node]; // else // tree[node]=tree[2*node+1]; // } // } // // // static void update(int node,int start,int end,int idx,int val) // { // if(start==end) // { // a[idx]=val; // tree[node]=val; // } // else // { // int mid=(start+end)/2; // if(idx>=start&&idx<=mid) // update(2*node,start,mid,idx,val); // else // update(2*node+1,mid+1,end,idx,val); // if(tree[2*node]<tree[2*node+1]) // tree[node]=tree[2*node]; // else // tree[node]=tree[2*node+1]; // } // } // // static int query(int node,int start,int end,int l,int r) // { // if(l>end||start>r) // return 100005; // if(l<=start&&r>=end) // return tree[node]; // int p1,p2; // int mid=(start+end)/2; // p1=query(2*node,start,mid,l,r); // p2=query(2*node+1,mid+1,end,l,r); // if(p1<p2) // return p1; // else // return p2; // } // // // //} } class Field{ long a; long b; Field(long a,long b){ this.a = Math.min(a, b); this.b = Math.max(a, b); } boolean greator(Field f){ return (this.a >= f.a && this.b >= f.b); } } class Node{ int a; int b; } class point{ int a; int b; } class MyComp2 implements Comparator<Node>{ @Override public int compare(Node o1, Node o2) { if( o1.b > o2.b){ return 1; }else if( o1.b < o2.b){ return -1; }else{ if(o1.a == o2.a){ return 0; }else if(o1.a > o2.a){ return 1; }else if(o1.a < o2.a){ return -1; } } return 0; } } class Card implements Comparable<Card> { int a,b; public Card(int w,int h) { this.a=w; this.b=h; } public int compareTo(Card that) { return this.a-that.a; } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const int MOD = (int)1e9 + 7; const int INF = (int)1e9; const long long LINF = (long long)1e18; const long double PI = acos((long double)-1); const long double EPS = 1e-9; inline long long gcd(long long a, long long b) { long long r; while (b) { r = a % b; a = b; b = r; } return a; } inline long long lcm(long long a, long long b) { return a / gcd(a, b) * b; } inline long long fpow(long long n, long long k, int p = MOD) { long long r = 1; for (; k; k >>= 1) { if (k & 1) r = r * n % p; n = n * n % p; } return r; } template <class T> inline int chkmin(T& a, const T& val) { return val < a ? a = val, 1 : 0; } template <class T> inline int chkmax(T& a, const T& val) { return a < val ? a = val, 1 : 0; } inline long long isqrt(long long k) { long long r = sqrt(k) + 1; while (r * r > k) r--; return r; } inline long long icbrt(long long k) { long long r = cbrt(k) + 1; while (r * r * r > k) r--; return r; } inline void addmod(int& a, int val, int p = MOD) { if ((a = (a + val)) >= p) a -= p; } inline void submod(int& a, int val, int p = MOD) { if ((a = (a - val)) < 0) a += p; } inline int mult(int a, int b, int p = MOD) { return (long long)a * b % p; } inline int inv(int a, int p = MOD) { return fpow(a, p - 2, p); } inline int sign(long double x) { return x < -EPS ? -1 : x > +EPS; } inline int sign(long double x, long double y) { return sign(x - y); } const int maxn = 1e5 + 5; int n; int a[maxn]; void solve() { cin >> n; for (int i = (0); i < (n); i++) cin >> a[i]; for (int i = (0); i < (n - 1); i++) a[i] -= a[i + 1]; for (int i = (0); i < (n - 1); i++) a[i] = abs(a[i]); long long mxeven = -LINF, mnodd = 0; long long ans = -LINF, tot = 0; for (int i = (0); i < (n - 1); i++) { if (!(i & 1)) { tot += a[i]; chkmax(ans, tot - mnodd); chkmax(mxeven, tot); } else { tot -= a[i]; chkmax(ans, mxeven - tot); chkmin(mnodd, tot); } } cout << ans << "\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); solve(); return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<long long> a(n); for (auto &s : a) scanf("%lld", &s); vector<long long> b(n - 1); for (int i = 0; i < n - 1; i++) { b[i] = abs(a[i] - a[i + 1]); } long long ans = 0, sum = 0; for (int i = 0; i < n - 1; i++) { if (i % 2 == 0) { sum += b[i]; } else { sum -= b[i]; } ans = max(ans, sum); if (sum < 0) sum = 0; } sum = 0; for (int i = 1; i < n - 1; i++) { if (i % 2 == 0) { sum -= b[i]; } else { sum += b[i]; } ans = max(ans, sum); if (sum < 0) sum = 0; } cout << ans << endl; } int main() { int t = 1; while (t--) solve(); }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; const int N = 100000; int a[N]; void solve() { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; } for (int i = 0; i < n - 1; i++) { a[i] = abs(a[i] - a[i + 1]); } n--; long long mx = INT_MIN; long long sm = 0; for (int i = 0; i < n; i++) { int x = ((i % 2 == 0) ? a[i] : -a[i]); sm = max(1LL * x, sm + x); mx = max(mx, sm); } sm = 0; for (int i = 0; i < n; i++) { int x = ((i % 2 == 1) ? a[i] : -a[i]); sm = max(1LL * x, sm + x); mx = max(mx, sm); } cout << mx; } int main() { solve(); getchar(); getchar(); }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int a[100000]; int b[100000]; int c[100000]; long long ayuda1; long long n; void entrarDatos() { for (int i = 0; i < n; i++) { cin >> a[i]; if (i > 0) { b[i - 1] = (a[i - 1] - a[i]); b[i - 1] = abs(b[i - 1]); ayuda1 = (i - 1) % 2; b[i - 1] = (b[i - 1] * pow(-1, ayuda1)); c[i - 1] = -1 * b[i - 1]; } } } int main() { long long addB = 0; long long auxiliar12 = INT_MIN, agregar1 = 0; cin >> n; entrarDatos(); for (int i = 0; i < n - 1; i++) { if (agregar1 == 0 || (agregar1 < b[i] && b[i] < 0) || (agregar1 < 0 && b[i] > 0)) agregar1 = b[i]; else agregar1 += b[i]; if (agregar1 > auxiliar12) auxiliar12 = agregar1; } agregar1 = 0; for (int i = 0; i < n - 1; i++) { if (agregar1 == 0 || (agregar1 < c[i] && c[i] < 0) || (agregar1 < 0 && c[i] > 0)) agregar1 = c[i]; else agregar1 += c[i]; if (agregar1 > auxiliar12) auxiliar12 = agregar1; } cout << auxiliar12; return 0; }
CPP
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Scanner; // author : iam_ss public class A { static int[][][] dp; static int[][][] store; static int[] arr; public static void main (String[] args) throws java.lang.Exception { //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); Scanner in = new Scanner(System.in); int n = in.nextInt(); arr = new int[n]; for(int i=0; i<n; i++) { arr[i] = in.nextInt(); } int[] rel1 = new int[n-1]; for(int i=0; i<n-1; i++) { rel1[i] = Math.abs(arr[i] - arr[i+1]); if(i % 2 == 0) { rel1[i] *= -1; } } int[] rel2 = new int[n-1]; for(int i=0; i<n-1; i++) { rel2[i] = Math.abs(arr[i] - arr[i+1]); if(i % 2 == 1) { rel2[i] *= -1; } } long max = -9999999999999l; long cur = 0; for(int i=0; i<rel1.length; i++) { cur += rel1[i]; max = Math.max(cur, max); if(cur < 0) { cur = 0; } } cur = 0; for(int i=0; i<rel2.length; i++) { cur += rel2[i]; max = Math.max(cur, max); if(cur < 0) { cur = 0; } } System.out.println(max); } }
JAVA
788_A. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows: <image> In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a. Input The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a. The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements. Output Print the only integer — the maximum value of f. Examples Input 5 1 4 2 3 1 Output 3 Input 4 1 5 4 7 Output 6 Note In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5]. In the second case maximal value of f is reachable only on the whole array.
2
7
#include <bits/stdc++.h> using namespace std; int store[100005]; long long ubound[100005], lbound[100005]; int cmp(const void* v1, const void* v2) { return *(int*)v1 - *(int*)v2; } int main(void) { int n; scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &store[i]); ubound[n - 1] = abs(store[n - 1] - store[n]); lbound[n - 1] = ubound[n - 1]; long long max = ubound[n - 1]; for (int i = n - 2; i >= 1; --i) { ubound[i] = lbound[i + 1] >= 0 ? abs(store[i] - store[i + 1]) : abs(store[i] - store[i + 1]) - lbound[i + 1]; lbound[i] = ubound[i + 1] >= 0 ? abs(store[i] - store[i + 1]) - ubound[i + 1] : abs(store[i] - store[i + 1]); if (ubound[i] > max) max = ubound[i]; } cout << max << endl; return 0; }
CPP