exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
sequencelengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | edb9ddfd4d6ee6448e23ed4da617335e | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | //package baobab;
import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) {
Solver solver = new Solver();
}
static class Solver {
IO io;
public Solver() {
this.io = new IO();
try {
solve();
} catch (RuntimeException e) {
if (!e.getMessage().equals("Clean exit")) {
throw e;
}
} finally {
io.close();
}
}
/****************************** START READING HERE ********************************/
int[] prim = generatePrimesUpTo(600);
void solve() {
int n = io.nextInt();
int m = io.nextInt();
// make connected by connecting 1 to everything else
if (m < n-1) done("Impossible");
List<String> ans = new ArrayList<>(m);
for (int i=2; i<=n; i+=1) ans.add("1 " + i);
if (ans.size() < m) {
for (int larger=min(n,600); larger>=2; larger--) {
if (knownPrime(larger)) {
for (int smaller=larger-1; smaller>=2; smaller--) {
ans.add(smaller + " " + larger);
if (ans.size() == m) break;
}
} else {
for (int smaller=larger-1; smaller>=2; smaller--) {
if (gcd(larger,smaller) == 1) {
ans.add(smaller + " " + larger);
if (ans.size() == m) break;
}
}
}
if (ans.size() == m) break;
}
}
if (ans.size() == m) {
io.println("Possible");
for (String line : ans) io.println(line);
} else io.println("Impossible");
}
boolean knownPrime(int n) {
return n < prim.length && prim[n] == 0;
}
/************************** UTILITY CODE BELOW THIS LINE **************************/
long MOD = (long)1e9 + 7;
boolean closeToZero(double v) {
// Check if double is close to zero, considering precision issues.
return Math.abs(v) <= 0.0000000000001;
}
class DrawGrid {
void draw(boolean[][] d) {
System.out.print(" ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" " + x + " ");
}
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print((d[y][x] ? "[x]" : "[ ]"));
}
System.out.println("");
}
}
void draw(int[][] d) {
int max = 1;
for (int y=0; y<d.length; y++) {
for (int x=0; x<d[0].length; x++) {
max = Math.max(max, ("" + d[y][x]).length());
}
}
System.out.print(" ");
String format = "%" + (max+2) + "s";
for (int x=0; x<d[0].length; x++) {
System.out.print(String.format(format, x) + " ");
}
format = "%" + (max) + "s";
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" [" + String.format(format, (d[y][x])) + "]");
}
System.out.println("");
}
}
}
class IDval implements Comparable<IDval> {
int id;
long val;
public IDval(int id, long val) {
this.val = val;
this.id = id;
}
@Override
public int compareTo(IDval o) {
if (this.val < o.val) return -1;
if (this.val > o.val) return 1;
return this.id - o.id;
}
}
private class ElementCounter {
private HashMap<Long, Integer> elements;
public ElementCounter() {
elements = new HashMap<>();
}
public void add(long element) {
int count = 1;
Integer prev = elements.get(element);
if (prev != null) count += prev;
elements.put(element, count);
}
public void remove(long element) {
int count = elements.remove(element);
count--;
if (count > 0) elements.put(element, count);
}
public int get(long element) {
Integer val = elements.get(element);
if (val == null) return 0;
return val;
}
public int size() {
return elements.size();
}
}
class StringCounter {
HashMap<String, Integer> elements;
public StringCounter() {
elements = new HashMap<>();
}
public void add(String identifier) {
int count = 1;
Integer prev = elements.get(identifier);
if (prev != null) count += prev;
elements.put(identifier, count);
}
public void remove(String identifier) {
int count = elements.remove(identifier);
count--;
if (count > 0) elements.put(identifier, count);
}
public long get(String identifier) {
Integer val = elements.get(identifier);
if (val == null) return 0;
return val;
}
public int size() {
return elements.size();
}
}
class DisjointSet {
/** Union Find / Disjoint Set data structure. */
int[] size;
int[] parent;
int componentCount;
public DisjointSet(int n) {
componentCount = n;
size = new int[n];
parent = new int[n];
for (int i=0; i<n; i++) parent[i] = i;
for (int i=0; i<n; i++) size[i] = 1;
}
public void join(int a, int b) {
/* Find roots */
int rootA = parent[a];
int rootB = parent[b];
while (rootA != parent[rootA]) rootA = parent[rootA];
while (rootB != parent[rootB]) rootB = parent[rootB];
if (rootA == rootB) {
/* Already in the same set */
return;
}
/* Merge smaller set into larger set. */
if (size[rootA] > size[rootB]) {
size[rootA] += size[rootB];
parent[rootB] = rootA;
} else {
size[rootB] += size[rootA];
parent[rootA] = rootB;
}
componentCount--;
}
}
class Trie {
int N;
int Z;
int nextFreeId;
int[][] pointers;
boolean[] end;
/** maxLenSum = maximum possible sum of length of words */
public Trie(int maxLenSum, int alphabetSize) {
this.N = maxLenSum;
this.Z = alphabetSize;
this.nextFreeId = 1;
pointers = new int[N+1][alphabetSize];
end = new boolean[N+1];
}
public void addWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) {
next = nextFreeId++;
pointers[curr][c] = next;
}
curr = next;
}
end[curr] = true;
}
public boolean hasWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) return false;
curr = next;
}
return end[curr];
}
}
private static class Prob {
/** For heavy calculations on probabilities, this class
* provides more accuracy & efficiency than doubles.
* Math explained: https://en.wikipedia.org/wiki/Log_probability
* Quick start:
* - Instantiate probabilities, eg. Prob a = new Prob(0.75)
* - add(), multiply() return new objects, can perform on nulls & NaNs.
* - get() returns probability as a readable double */
/** Logarithmized probability. Note: 0% represented by logP NaN. */
private double logP;
/** Construct instance with real probability. */
public Prob(double real) {
if (real > 0) this.logP = Math.log(real);
else this.logP = Double.NaN;
}
/** Construct instance with already logarithmized value. */
static boolean dontLogAgain = true;
public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) {
this.logP = logP;
}
/** Returns real probability as a double. */
public double get() {
return Math.exp(logP);
}
@Override
public String toString() {
return ""+get();
}
/***************** STATIC METHODS BELOW ********************/
/** Note: returns NaN only when a && b are both NaN/null. */
public static Prob add(Prob a, Prob b) {
if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
if (nullOrNaN(a)) return copy(b);
if (nullOrNaN(b)) return copy(a);
double x = Math.max(a.logP, b.logP);
double y = Math.min(a.logP, b.logP);
double sum = x + Math.log(1 + Math.exp(y - x));
return new Prob(sum, dontLogAgain);
}
/** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */
public static Prob multiply(Prob a, Prob b) {
if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
return new Prob(a.logP + b.logP, dontLogAgain);
}
/** Returns true if p is null or NaN. */
private static boolean nullOrNaN(Prob p) {
return (p == null || Double.isNaN(p.logP));
}
/** Returns a new instance with the same value as original. */
private static Prob copy(Prob original) {
return new Prob(original.logP, dontLogAgain);
}
}
class Binary implements Comparable<Binary> {
/**
* Use example: Binary b = new Binary(Long.toBinaryString(53249834L));
*
* When manipulating small binary strings, instantiate new Binary(string)
* When just reading large binary strings, instantiate new Binary(string,true)
* get(int i) returns a character '1' or '0', not an int.
*/
private boolean[] d;
private int first; // Starting from left, the first (most remarkable) '1'
public int length;
public Binary(String binaryString) {
this(binaryString, false);
}
public Binary(String binaryString, boolean initWithMinArraySize) {
length = binaryString.length();
int size = Math.max(2*length, 1);
first = length/4;
if (initWithMinArraySize) {
first = 0;
size = Math.max(length, 1);
}
d = new boolean[size];
for (int i=0; i<length; i++) {
if (binaryString.charAt(i) == '1') d[i+first] = true;
}
}
public void addFirst(char c) {
if (first-1 < 0) doubleArraySize();
first--;
d[first] = (c == '1' ? true : false);
length++;
}
public void addLast(char c) {
if (first+length >= d.length) doubleArraySize();
d[first+length] = (c == '1' ? true : false);
length++;
}
private void doubleArraySize() {
boolean[] bigArray = new boolean[(d.length+1) * 2];
int newFirst = bigArray.length / 4;
for (int i=0; i<length; i++) {
bigArray[i + newFirst] = d[i + first];
}
first = newFirst;
d = bigArray;
}
public boolean flip(int i) {
boolean value = (this.d[first+i] ? false : true);
this.d[first+i] = value;
return value;
}
public void set(int i, char c) {
boolean value = (c == '1' ? true : false);
this.d[first+i] = value;
}
public char get(int i) {
return (this.d[first+i] ? '1' : '0');
}
@Override
public int compareTo(Binary o) {
if (this.length != o.length) return this.length - o.length;
int len = this.length;
for (int i=0; i<len; i++) {
int diff = this.get(i) - o.get(i);
if (diff != 0) return diff;
}
return 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i=0; i<length; i++) {
sb.append(d[i+first] ? '1' : '0');
}
return sb.toString();
}
}
/************************** Range queries **************************/
class FenwickMin {
long n;
long[] original;
long[] bottomUp;
long[] topDown;
public FenwickMin(int n) {
this.n = n;
original = new long[n+2];
bottomUp = new long[n+2];
topDown = new long[n+2];
}
public void set(int modifiedNode, long value) {
long replaced = original[modifiedNode];
original[modifiedNode] = value;
// Update left tree
int i = modifiedNode;
long v = value;
while (i <= n) {
if (v > bottomUp[i]) {
if (replaced == bottomUp[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i-x;
v = Math.min(v, bottomUp[child]);
}
} else break;
}
if (v == bottomUp[i]) break;
bottomUp[i] = v;
i += (i&-i);
}
// Update right tree
i = modifiedNode;
v = value;
while (i > 0) {
if (v > topDown[i]) {
if (replaced == topDown[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i+x;
if (child > n+1) break;
v = Math.min(v, topDown[child]);
}
} else break;
}
if (v == topDown[i]) break;
topDown[i] = v;
i -= (i&-i);
}
}
public long getMin(int a, int b) {
long min = original[a];
int prev = a;
int curr = prev + (prev&-prev); // parent right hand side
while (curr <= b) {
min = Math.min(min, topDown[prev]); // value from the other tree
prev = curr;
curr = prev + (prev&-prev);;
}
min = Math.min(min, original[prev]);
prev = b;
curr = prev - (prev&-prev); // parent left hand side
while (curr >= a) {
min = Math.min(min,bottomUp[prev]); // value from the other tree
prev = curr;
curr = prev - (prev&-prev);
}
return min;
}
}
class FenwickSum {
public long[] d;
public FenwickSum(int n) {
d=new long[n+1];
}
/** a[0] must be unused. */
public FenwickSum(long[] a) {
d=new long[a.length];
for (int i=1; i<a.length; i++) {
modify(i, a[i]);
}
}
/** Do not modify i=0. */
void modify(int i, long v) {
while (i<d.length) {
d[i] += v;
// Move to next uplink on the RIGHT side of i
i += (i&-i);
}
}
/** Returns sum from a to b, *BOTH* inclusive. */
long getSum(int a, int b) {
return getSum(b) - getSum(a-1);
}
private long getSum(int i) {
long sum = 0;
while (i>0) {
sum += d[i];
// Move to next uplink on the LEFT side of i
i -= (i&-i);
}
return sum;
}
}
class SegmentTree {
/** Query sums with log(n) modifyRange */
int N;
long[] p;
public SegmentTree(int n) {
/* TODO: Test that this works. */
for (N=2; N<n; N++) N *= 2;
p = new long[2*N];
}
public void modifyRange(int a, int b, long change) {
muuta(a, change);
muuta(b+1, -change);
}
void muuta(int k, long muutos) {
k += N;
p[k] += muutos;
for (k /= 2; k >= 1; k /= 2) {
p[k] = p[2*k] + p[2*k+1];
}
}
public long get(int k) {
int a = N;
int b = k+N;
long s = 0;
while (a <= b) {
if (a%2 == 1) s += p[a++];
if (b%2 == 0) s += p[b--];
a /= 2;
b /= 2;
}
return s;
}
}
/***************************** Graphs *****************************/
List<Integer>[] toGraph(IO io, int n) {
List<Integer>[] g = new ArrayList[n+1];
for (int i=1; i<=n; i++) g[i] = new ArrayList<>();
for (int i=1; i<=n-1; i++) {
int a = io.nextInt();
int b = io.nextInt();
g[a].add(b);
g[b].add(a);
}
return g;
}
class Graph {
HashMap<Long, List<Long>> edges;
public Graph() {
edges = new HashMap<>();
}
List<Long> getSetNeighbors(Long node) {
List<Long> neighbors = edges.get(node);
if (neighbors == null) {
neighbors = new ArrayList<>();
edges.put(node, neighbors);
}
return neighbors;
}
void addBiEdge(Long a, Long b) {
addEdge(a, b);
addEdge(b, a);
}
void addEdge(Long from, Long to) {
getSetNeighbors(to); // make sure all have initialized lists
List<Long> neighbors = getSetNeighbors(from);
neighbors.add(to);
}
// topoSort variables
int UNTOUCHED = 0;
int FINISHED = 2;
int INPROGRESS = 1;
HashMap<Long, Integer> vis;
List<Long> topoAns;
List<Long> failDueToCycle = new ArrayList<Long>() {{ add(-1L); }};
List<Long> topoSort() {
topoAns = new ArrayList<>();
vis = new HashMap<>();
for (Long a : edges.keySet()) {
if (!topoDFS(a)) return failDueToCycle;
}
Collections.reverse(topoAns);
return topoAns;
}
boolean topoDFS(long curr) {
Integer status = vis.get(curr);
if (status == null) status = UNTOUCHED;
if (status == FINISHED) return true;
if (status == INPROGRESS) {
return false;
}
vis.put(curr, INPROGRESS);
for (long next : edges.get(curr)) {
if (!topoDFS(next)) return false;
}
vis.put(curr, FINISHED);
topoAns.add(curr);
return true;
}
}
public class StronglyConnectedComponents {
/** Kosaraju's algorithm */
ArrayList<Integer>[] forw;
ArrayList<Integer>[] bacw;
/** Use: getCount(2, new int[] {1,2}, new int[] {2,1}) */
public int getCount(int n, int[] mista, int[] minne) {
forw = new ArrayList[n+1];
bacw = new ArrayList[n+1];
for (int i=1; i<=n; i++) {
forw[i] = new ArrayList<Integer>();
bacw[i] = new ArrayList<Integer>();
}
for (int i=0; i<mista.length; i++) {
int a = mista[i];
int b = minne[i];
forw[a].add(b);
bacw[b].add(a);
}
int count = 0;
List<Integer> list = new ArrayList<Integer>();
boolean[] visited = new boolean[n+1];
for (int i=1; i<=n; i++) {
dfsForward(i, visited, list);
}
visited = new boolean[n+1];
for (int i=n-1; i>=0; i--) {
int node = list.get(i);
if (visited[node]) continue;
count++;
dfsBackward(node, visited);
}
return count;
}
public void dfsForward(int i, boolean[] visited, List<Integer> list) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : forw[i]) {
dfsForward(neighbor, visited, list);
}
list.add(i);
}
public void dfsBackward(int i, boolean[] visited) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : bacw[i]) {
dfsBackward(neighbor, visited);
}
}
}
class LCAFinder {
/* O(n log n) Initialize: new LCAFinder(graph)
* O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */
int[] nodes;
int[] depths;
int[] entries;
int pointer;
FenwickMin fenwick;
public LCAFinder(List<Integer>[] graph) {
this.nodes = new int[(int)10e6];
this.depths = new int[(int)10e6];
this.entries = new int[graph.length];
this.pointer = 1;
boolean[] visited = new boolean[graph.length+1];
dfs(1, 0, graph, visited);
fenwick = new FenwickMin(pointer-1);
for (int i=1; i<pointer; i++) {
fenwick.set(i, depths[i] * 1000000L + i);
}
}
private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) {
visited[node] = true;
entries[node] = pointer;
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
for (int neighbor : graph[node]) {
if (visited[neighbor]) continue;
dfs(neighbor, depth+1, graph, visited);
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
}
}
public int find(int a, int b) {
int left = entries[a];
int right = entries[b];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
long mixedBag = fenwick.getMin(left, right);
int index = (int) (mixedBag % 1000000L);
return nodes[index];
}
}
/**************************** Geometry ****************************/
class Point {
int y;
int x;
public Point(int y, int x) {
this.y = y;
this.x = x;
}
}
boolean segmentsIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {
// Returns true if segment 1-2 intersects segment 3-4
if (x1 == x2 && x3 == x4) {
// Both segments are vertical
if (x1 != x3) return false;
if (min(y1,y2) < min(y3,y4)) {
return max(y1,y2) >= min(y3,y4);
} else {
return max(y3,y4) >= min(y1,y2);
}
}
if (x1 == x2) {
// Only segment 1-2 is vertical. Does segment 3-4 cross it? y = a*x + b
double a34 = (y4-y3)/(x4-x3);
double b34 = y3 - a34*x3;
double y = a34 * x1 + b34;
return y >= min(y1,y2) && y <= max(y1,y2) && x1 >= min(x3,x4) && x1 <= max(x3,x4);
}
if (x3 == x4) {
// Only segment 3-4 is vertical. Does segment 1-2 cross it? y = a*x + b
double a12 = (y2-y1)/(x2-x1);
double b12 = y1 - a12*x1;
double y = a12 * x3 + b12;
return y >= min(y3,y4) && y <= max(y3,y4) && x3 >= min(x1,x2) && x3 <= max(x1,x2);
}
double a12 = (y2-y1)/(x2-x1);
double b12 = y1 - a12*x1;
double a34 = (y4-y3)/(x4-x3);
double b34 = y3 - a34*x3;
if (closeToZero(a12 - a34)) {
// Parallel lines
return closeToZero(b12 - b34);
}
// Non parallel non vertical lines intersect at x. Is x part of both segments?
double x = -(b12-b34)/(a12-a34);
return x >= min(x1,x2) && x <= max(x1,x2) && x >= min(x3,x4) && x <= max(x3,x4);
}
boolean pointInsideRectangle(Point p, List<Point> r) {
Point a = r.get(0);
Point b = r.get(1);
Point c = r.get(2);
Point d = r.get(3);
double apd = areaOfTriangle(a, p, d);
double dpc = areaOfTriangle(d, p, c);
double cpb = areaOfTriangle(c, p, b);
double pba = areaOfTriangle(p, b, a);
double sumOfAreas = apd + dpc + cpb + pba;
if (closeToZero(sumOfAreas - areaOfRectangle(r))) {
if (closeToZero(apd) || closeToZero(dpc) || closeToZero(cpb) || closeToZero(pba)) {
return false;
}
return true;
}
return false;
}
double areaOfTriangle(Point a, Point b, Point c) {
return 0.5 * Math.abs((a.x-c.x)*(b.y-a.y)-(a.x-b.x)*(c.y-a.y));
}
double areaOfRectangle(List<Point> r) {
double side1xDiff = r.get(0).x - r.get(1).x;
double side1yDiff = r.get(0).y - r.get(1).y;
double side2xDiff = r.get(1).x - r.get(2).x;
double side2yDiff = r.get(1).y - r.get(2).y;
double side1 = Math.sqrt(side1xDiff * side1xDiff + side1yDiff * side1yDiff);
double side2 = Math.sqrt(side2xDiff * side2xDiff + side2yDiff * side2yDiff);
return side1 * side2;
}
boolean pointsOnSameLine(double x1, double y1, double x2, double y2, double x3, double y3) {
double areaTimes2 = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2);
return (closeToZero(areaTimes2));
}
class PointToLineSegmentDistanceCalculator {
// Just call this
double minDistFromPointToLineSegment(double point_x, double point_y, double x1, double y1, double x2, double y2) {
return Math.sqrt(distToSegmentSquared(point_x, point_y, x1, y1, x2, y2));
}
private double distToSegmentSquared(double point_x, double point_y, double x1, double y1, double x2, double y2) {
double l2 = dist2(x1,y1,x2,y2);
if (l2 == 0) return dist2(point_x, point_y, x1, y1);
double t = ((point_x - x1) * (x2 - x1) + (point_y - y1) * (y2 - y1)) / l2;
if (t < 0) return dist2(point_x, point_y, x1, y1);
if (t > 1) return dist2(point_x, point_y, x2, y2);
double com_x = x1 + t * (x2 - x1);
double com_y = y1 + t * (y2 - y1);
return dist2(point_x, point_y, com_x, com_y);
}
private double dist2(double x1, double y1, double x2, double y2) {
return Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2);
}
}
/****************************** Math ******************************/
long pow(long base, int exp) {
if (exp == 0) return 1L;
long x = pow(base, exp/2);
long ans = x * x;
if (exp % 2 != 0) ans *= base;
return ans;
}
long gcd(long... v) {
/** Chained calls to Euclidean algorithm. */
if (v.length == 1) return v[0];
long ans = gcd(v[1], v[0]);
for (int i=2; i<v.length; i++) {
ans = gcd(ans, v[i]);
}
return ans;
}
long gcd(long a, long b) {
/** Euclidean algorithm. */
if (b == 0) return a;
return gcd(b, a%b);
}
int[] generatePrimesUpTo(int last) {
/* Sieve of Eratosthenes. Practically O(n). Values of 0 indicate primes. */
int[] div = new int[last+1];
for (int x=2; x<=last; x++) {
if (div[x] > 0) continue;
for (int u=2*x; u<=last; u+=x) {
div[u] = x;
}
}
return div;
}
long lcm(long a, long b) {
/** Least common multiple */
return a * b / gcd(a,b);
}
class BaseConverter {
/* Palauttaa luvun esityksen kannassa base */
public String convert(Long number, int base) {
return Long.toString(number, base);
}
/* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku Stringinä kannassa baseFrom */
public String convert(String number, int baseFrom, int baseTo) {
return Long.toString(Long.parseLong(number, baseFrom), baseTo);
}
/* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */
public long longify(String number, int baseFrom) {
return Long.parseLong(number, baseFrom);
}
}
class BinomialCoefficients {
/** Total number of K sized unique combinations from pool of size N (unordered)
N! / ( K! (N - K)! ) */
/** For simple queries where output fits in long. */
public long biCo(long n, long k) {
long r = 1;
if (k > n) return 0;
for (long d = 1; d <= k; d++) {
r *= n--;
r /= d;
}
return r;
}
/** For multiple queries with same n, different k. */
public long[] precalcBinomialCoefficientsK(int n, int maxK) {
long v[] = new long[maxK+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,maxK); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
}
}
return v;
}
/** When output needs % MOD. */
public long[] precalcBinomialCoefficientsK(int n, int k, long M) {
long v[] = new long[k+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,k); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
v[j] %= M;
}
}
return v;
}
}
/**************************** Strings ****************************/
class Zalgo {
public int pisinEsiintyma(String haku, String kohde) {
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
int max = 0;
for (int i=haku.length(); i<z.length; i++) {
max = Math.max(max, z[i]);
}
return max;
}
public int[] toZarray(char[] s) {
int n = s.length;
int[] z = new int[n];
int a = 0, b = 0;
for (int i = 1; i < n; i++) {
if (i > b) {
for (int j = i; j < n && s[j - i] == s[j]; j++) z[i]++;
}
else {
z[i] = z[i - a];
if (i + z[i - a] > b) {
for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++;
a = i;
b = i + z[i] - 1;
}
}
}
return z;
}
public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) {
// this is alternative use case
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
List<Integer> indexes = new ArrayList<>();
for (int i=haku.length(); i<z.length; i++) {
if (z[i] < haku.length()) continue;
indexes.add(i);
}
return indexes;
}
}
class StringHasher {
class HashedString {
long[] hashes;
long[] modifiers;
public HashedString(long[] hashes, long[] modifiers) {
this.hashes = hashes;
this.modifiers = modifiers;
}
}
long P;
long M;
public StringHasher() {
initializePandM();
}
HashedString hashString(String s) {
int n = s.length();
long[] hashes = new long[n];
long[] modifiers = new long[n];
hashes[0] = s.charAt(0);
modifiers[0] = 1;
for (int i=1; i<n; i++) {
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
modifiers[i] = (modifiers[i-1] * P) % M;
}
return new HashedString(hashes, modifiers);
}
/**
* Indices are inclusive.
*/
long getHash(HashedString hashedString, int startIndex, int endIndex) {
long[] hashes = hashedString.hashes;
long[] modifiers = hashedString.modifiers;
long result = hashes[endIndex];
if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M;
if (result < 0) result += M;
return result;
}
// Less interesting methods below
/**
* Efficient for 2 input parameter strings in particular.
*/
HashedString[] hashString(String first, String second) {
HashedString[] array = new HashedString[2];
int n = first.length();
long[] modifiers = new long[n];
modifiers[0] = 1;
long[] firstHashes = new long[n];
firstHashes[0] = first.charAt(0);
array[0] = new HashedString(firstHashes, modifiers);
long[] secondHashes = new long[n];
secondHashes[0] = second.charAt(0);
array[1] = new HashedString(secondHashes, modifiers);
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M;
secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M;
}
return array;
}
/**
* Efficient for 3+ strings
* More efficient than multiple hashString calls IF strings are same length.
*/
HashedString[] hashString(String... strings) {
HashedString[] array = new HashedString[strings.length];
int n = strings[0].length();
long[] modifiers = new long[n];
modifiers[0] = 1;
for (int j=0; j<strings.length; j++) {
// if all strings are not same length, defer work to another method
if (strings[j].length() != n) {
for (int i=0; i<n; i++) {
array[i] = hashString(strings[i]);
}
return array;
}
// otherwise initialize stuff
long[] hashes = new long[n];
hashes[0] = strings[j].charAt(0);
array[j] = new HashedString(hashes, modifiers);
}
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
for (int j=0; j<strings.length; j++) {
String s = strings[j];
long[] hashes = array[j].hashes;
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
}
}
return array;
}
void initializePandM() {
ArrayList<Long> modOptions = new ArrayList<>(20);
modOptions.add(353873237L);
modOptions.add(353875897L);
modOptions.add(353878703L);
modOptions.add(353882671L);
modOptions.add(353885303L);
modOptions.add(353888377L);
modOptions.add(353893457L);
P = modOptions.get(new Random().nextInt(modOptions.size()));
modOptions.clear();
modOptions.add(452940277L);
modOptions.add(452947687L);
modOptions.add(464478431L);
modOptions.add(468098221L);
modOptions.add(470374601L);
modOptions.add(472879717L);
modOptions.add(472881973L);
M = modOptions.get(new Random().nextInt(modOptions.size()));
}
}
/*************************** Technical ***************************/
private class IO extends PrintWriter {
private InputStreamReader r;
private static final int BUFSIZE = 1 << 15;
private char[] buf;
private int bufc;
private int bufi;
private StringBuilder sb;
public IO() {
super(new BufferedOutputStream(System.out));
r = new InputStreamReader(System.in);
buf = new char[BUFSIZE];
bufc = 0;
bufi = 0;
sb = new StringBuilder();
}
/** Print, flush, return nextInt. */
private int queryInt(String s) {
io.println(s);
io.flush();
return nextInt();
}
/** Print, flush, return nextLong. */
private long queryLong(String s) {
io.println(s);
io.flush();
return nextLong();
}
/** Print, flush, return next word. */
private String queryNext(String s) {
io.println(s);
io.flush();
return next();
}
private void fillBuf() throws IOException {
bufi = 0;
bufc = 0;
while(bufc == 0) {
bufc = r.read(buf, 0, BUFSIZE);
if(bufc == -1) {
bufc = 0;
return;
}
}
}
private boolean pumpBuf() throws IOException {
if(bufi == bufc) {
fillBuf();
}
return bufc != 0;
}
private boolean isDelimiter(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
}
private void eatDelimiters() throws IOException {
while(true) {
if(bufi == bufc) {
fillBuf();
if(bufc == 0) throw new RuntimeException("IO: Out of input.");
}
if(!isDelimiter(buf[bufi])) break;
++bufi;
}
}
public String next() {
try {
sb.setLength(0);
eatDelimiters();
int start = bufi;
while(true) {
if(bufi == bufc) {
sb.append(buf, start, bufi - start);
fillBuf();
start = 0;
if(bufc == 0) break;
}
if(isDelimiter(buf[bufi])) break;
++bufi;
}
sb.append(buf, start, bufi - start);
return sb.toString();
} catch(IOException e) {
throw new RuntimeException("IO.next: Caught IOException.");
}
}
public int nextInt() {
try {
int ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextInt: Invalid int.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int.");
ret *= 10;
ret -= (int)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int.");
} else {
throw new RuntimeException("IO.nextInt: Invalid int.");
}
++bufi;
}
if(positive) {
if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextInt: Caught IOException.");
}
}
public long nextLong() {
try {
long ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextLong: Invalid long.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret *= 10;
ret -= (long)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long.");
} else {
throw new RuntimeException("IO.nextLong: Invalid long.");
}
++bufi;
}
if(positive) {
if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextLong: Caught IOException.");
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
void print(Object output) {
io.println(output);
}
void done(Object output) {
print(output);
done();
}
void done() {
io.close();
throw new RuntimeException("Clean exit");
}
long min(long... v) {
long ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
double min(double... v) {
double ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
int min(int... v) {
int ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.min(ans, v[i]);
}
return ans;
}
long max(long... v) {
long ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
double max(double... v) {
double ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
int max(int... v) {
int ans = v[0];
for (int i=1; i<v.length; i++) {
ans = Math.max(ans, v[i]);
}
return ans;
}
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | df9a81cd4e21ca3eaed55c8c926f5260 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jenish
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DRelativelyPrimeGraph solver = new DRelativelyPrimeGraph();
solver.solve(1, in, out);
out.close();
}
static class DRelativelyPrimeGraph {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int m = in.scanInt();
if (m < n - 1) {
out.println("Impossible");
} else if (m == n - 1) {
out.println("Possible");
for (int i = 2; i <= n; i++) {
out.println(1 + " " + i);
}
} else {
int ramiain = m - (n - 1);
long sum = 0;
for (int i = 2; i <= n; i++) sum += phi(i) - 1;
if (sum >= ramiain) {
out.println("Possible");
ramiain = m;
for (int i = 2; i <= n; i++) {
out.println(1 + " " + i);
ramiain--;
}
for (int i = n; i >= 2; i--) {
if (ramiain > 0) {
boolean visted[] = new boolean[n + 1];
int result = i;
int temp = i;
for (int p = 2; p * p <= temp; ++p) {
if (temp % p == 0) {
while (temp % p == 0) temp /= p;
result -= result / p;
if (p != 0) {
for (int j = p; j < i; j += p) {
visted[j] = true;
}
}
}
}
if (temp > 1) {
for (int j = temp; j < i; j += temp) {
visted[j] = true;
}
}
for (int j = 2; j <= i - 1 && ramiain > 0; j++) {
if (!visted[j]) {
ramiain--;
out.println(j + " " + i);
}
}
}
}
} else {
out.println("Impossible");
}
}
}
int phi(int n) {
int result = n;
for (int p = 2; p * p <= n; ++p) {
if (n % p == 0) {
while (n % p == 0)
n /= p;
result -= result / p;
}
}
if (n > 1)
result -= result / n;
return result;
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
public int scanInt() {
int I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | aefc58610bdfafb8d762b08bd1e5721e | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | //package aug;
import java.io.*;
import java.util.*;
public class EdRnd47 {
InputStream is;
PrintWriter out;
String INPUT = "";
//boolean codechef=false;
boolean codechef=true;
void solve()
{
int n=ni(),m=ni(),cnt=0;
Pair[] ans=new Pair[m];
HashSet<Integer> set=new HashSet<>();
for(int i=1;i<n;i++)
{
for(int j=i+1;j<=n;j++)
{
if(gcd(i,j)==1)
{
if(cnt<m)
{
ans[cnt++]=new Pair(i,j);
set.add(i);
set.add(j);
}
else break;
}
}
if(cnt>=m)break;
}
if(set.size()!=n)
{
out.println("Impossible");
}
else if(cnt!=m)
{
out.println("Impossible");
}
else
{
out.println("Possible");
for(Pair pr:ans)
{
out.println(pr.a+" "+pr.b);
}
}
}
public static int[] roughFactorFast(int n, int[] lpf)
{
int[] rf = new int[9];
int q = 0;
int pre = -1;
while(lpf[n] > 0){
int p = lpf[n];
if(q == 0 || p != pre){
rf[q++] = p;
pre = p;
}else{
// rf[q-1] *= p;
}
n /= p;
}
return Arrays.copyOf(rf, q);
}
public static int[] enumLowestPrimeFactors(int n) {
int tot = 0;
int[] lpf = new int[n + 1];
int u = n + 32;
double lu = Math.log(u);
int[] primes = new int[(int) (u / lu + u / lu / lu * 1.5)];
for (int i = 2; i <= n; i++)
lpf[i] = i;
for (int p = 2; p <= n; p++) {
if (lpf[p] == p)
primes[tot++] = p;
int tmp;
for (int i = 0; i < tot && primes[i] <= lpf[p] && (tmp = primes[i] * p) <= n; i++) {
lpf[tmp] = primes[i];
}
}
return lpf;
}
static long gcd(long a,long b)
{
if(a==0)return b;
return gcd(b%a,a);
}
static class Pair
{
int a,b;
public Pair(int a,int b)
{
this.a=a;
this.b=b;
}
}
static int pow(int a, int b, int p)
{
long ans = 1, base = a;
while (b!=0)
{
if ((b & 1)!=0)
{
ans *= base;
ans%= p;
}
base *= base;
base%= p;
b >>= 1;
}
return (int)ans;
}
static int inv(int x, int p)
{
return pow(x, p - 2, p);
}
void run() throws Exception
{
if(codechef)oj=true;
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception {new EdRnd47().run();}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 3739b4d51f7cf321e96d48014f334513 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
private static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int m = s.nextInt();
List<Object[]> edges = new ArrayList<> ();
if (m < n - 1) {
System.out.println("Impossible");
return;
}
for (int i = 1; i < n; ++i) {
edges.add(new Object[] {i, i + 1});
}
for (int i = 1; edges.size() < m && i < n; ++i) {
for (int j = i + 2; edges.size() < m && j <= n; ++j) {
if (i == 1 || gcd(i, j) == 1) {
edges.add(new Object[] {i, j});
}
}
}
if (edges.size() < m) {
System.out.println("Impossible");
return;
}
System.out.println("Possible");
for (Object[] edge : edges) {
System.out.println(edge[0] + " " + edge[1]);
}
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 2ea87fa964202f195661cbf5fbf53b6d | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
* @author pttrung
*/
public class D_Edu_Round_47 {
public static long MOD = 1000000007;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int m = in.nextInt();
if (m < n - 1) {
out.println("Impossible");
} else {
ArrayList<Point> list = new ArrayList();
for (int i = 2; i <= n && m > 0; i++) {
list.add(new Point(1, i));
m--;
}
for (int i = 2; i <= n && m > 0; i++) {
for (int j = i + 1; j <= n && m > 0; j++) {
if (gcd(i, j) == 1) {
list.add(new Point(i, j));
m--;
}
}
}
if (m == 0) {
out.println("Possible");
for (Point p : list) {
out.println(p.x + " " + p.y);
}
} else {
out.println("Impossible");
}
}
out.close();
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | f21e68022f1427f26cdfa1fc1e9fd8fd | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class Relatively_Prime_Graph {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int m = scn.nextInt();
ArrayList<pair> pr = new ArrayList<>();
for (int i = 1; i <= n&&pr.size()<m; i++) {
for(int j=i+1;j<=n&&pr.size()<m;j++){
if(i==1){
pr.add(new pair(i,j));
}else if(gcd(j,i)==1){
pr.add(new pair(i,j));
}
}
}
if(pr.size()<m||(pr.size()==m&&m<n-1)){
System.out.println("Impossible");
}else{
StringBuilder sb=new StringBuilder();
sb.append("Possible\n");
for(pair v:pr){
sb.append(v.val+" "+v.val2+"\n");
}
System.out.println(sb);
}
}
private static int gcd(int j, int i) {
// TODO Auto-generated method stub
if(i==0){
return j;
}
return gcd(i, j%i);
}
public static class pair {
int val;
int val2;
pair(int v1,int v2){
val=v1;
val2=v2;
}
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | e97bac89ba143130bf83f86742e6ae28 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.math.BigInteger;
import java.util.regex.*;
public class Myclass {
public static ArrayList a[]=new ArrayList[200001];
/*public static int cat[]=new int [200001];
static int upto[]=new int[200001];
static int maxi[]=new int[200001];
static boolean visited[]=new boolean [200001];
static void dfs(int n,int p)
{
visited[n]=true;
if(cat[n]==1)
{
upto[n]=upto[p]+1;
}
maxi[n]=Math.max(maxi[p], upto[n]);
for(int i=0;i<a[n].size();i++)
{
int idx=(int) a[n].get(i);
if(!visited[idx])
{
dfs(idx,n);
}
}
}*/
/*static boolean visited[]=new boolean [200001];
static PriorityQueue<pair>one =new PriorityQueue<>();
static PriorityQueue<pair>two =new PriorityQueue<>();
static PriorityQueue<pair>three =new PriorityQueue<>();
static long a[]=new long [200001];
public static void f(int x,int j)
{
if(x==1)
one.add(new pair(a[j],j));
else if(x==2)
two.add(new pair(a[j],j));
else
three.add(new pair(a[j],j));
}*/
public static long dp[][]=new long[5001][5001];
public static void nCr()
{
dp[0][0]=1;
for(int i=1;i<=5000;i++)
{
for(int j=1;j<i;j++)
{
dp[i][j]=((dp[i-1][j]%(mod-1))+((dp[i-1][j-1])%(mod-1)))%(mod-1);
}
dp[i][0]=1;
dp[i][i]=1;
}
}
public static void main(String[] args) throws InterruptedException
{
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n=in.nextInt();
int m=in.nextInt();
Vector<pair>v=new Vector<>();
int cnt=0;
for(int i=1;i<n;i++)
{
for(int j=i+1;j<=n;j++)
{
if(cnt==m)
{
break;
}
if(GCD(i,j)==1)
{
v.add(new pair(i,j));
cnt++;
continue;
}
}
if(cnt==m)
break;
}
if(cnt!=m ||m<n-1)
{
pw.println("Impossible");
}
else
{
pw.println("Possible");
for(int i=0;i<m;i++)
{
pw.println(v.get(i));
}
}
pw.flush();
pw.close();
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
static class tri implements Comparable<tri> {
int p, c, l;
tri(int p, int c, int l) {
this.p = p;
this.c = c;
this.l = l;
}
public int compareTo(tri o) {
return Integer.compare(l, o.l);
}
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static long mod = 1000000007;
public static int d;
public static int p;
public static int q;
public static int[] suffle(int[] a,Random gen)
{
int n = a.length;
for(int i=0;i<n;i++)
{
int ind = gen.nextInt(n-i)+i;
int temp = a[ind];
a[ind] = a[i];
a[i] = temp;
}
return a;
}
public static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
public static HashSet<Integer> primeFactorization(int n)
{
HashSet<Integer> a =new HashSet<Integer>();
for(int i=2;i*i<=n;i++)
{
while(n%i==0)
{
a.add(i);
n/=i;
}
}
if(n!=1)
a.add(n);
return a;
}
public static void sieve(boolean[] isPrime,int n)
{
for(int i=1;i<n;i++)
isPrime[i] = true;
isPrime[0] = false;
isPrime[1] = false;
for(int i=2;i*i<n;i++)
{
if(isPrime[i] == true)
{
for(int j=(2*i);j<n;j+=i)
isPrime[j] = false;
}
}
}
public static int GCD(int a,int b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static long GCD(long a,long b)
{
if(b==0)
return a;
else
return GCD(b,a%b);
}
public static void extendedEuclid(int A,int B)
{
if(B==0)
{
d = A;
p = 1 ;
q = 0;
}
else
{
extendedEuclid(B, A%B);
int temp = p;
p = q;
q = temp - (A/B)*q;
}
}
public static long LCM(long a,long b)
{
return (a*b)/GCD(a,b);
}
public static int LCM(int a,int b)
{
return (a*b)/GCD(a,b);
}
public static int binaryExponentiation(int x,int n)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static long binaryExponentiation(long x,long n)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=x*x;
n=n/2;
}
return result;
}
public static int modularExponentiation(int x,int n,int M)
{
int result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result * x)%M;
x=(x%M*x)%M;
n=n/2;
}
return result;
}
public static long me(long x,long n,long M)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result%M * x%M)%M;
x=(x%M * x%M)%M;
}
return result;
}
public static long modularExponentiation(long x,long n,long M)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=(result%M * x%M)%M;
x=(x%M * x%M)%M;
n=n/2;
}
return result;
}
public static long modInverse(int A,int M)
{
return modularExponentiation(A,M-2,M);
}
public static long modInverse(long A,long M)
{
return me(A,M-2,M);
}
public static boolean isPrime(int n)
{
if (n <= 1) return false;
if (n <= 3) return true;
if (n%2 == 0 || n%3 == 0)
return false;
for (int i=5; i*i<=n; i=i+6)
{
if (n%i == 0 || n%(i+2) == 0)
return false;
}
return true;
}
public static long[] shuffle(long[] a, Random gen){
for(int i = 0, n = a.length;i < n;i++){
int ind = gen.nextInt(n-i)+i;
long d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
static class pair implements Comparable<pair>
{
Integer x;
Integer y;
pair(int a,int m)
{
this.x=a;
this.y=m;
}
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
return result;
}
public String toString()
{
return x+" "+y;
}
public boolean equals(Object o)
{
if (o instanceof pair)
{
pair p = (pair)o;
return p.x == x && p.y == y ;
}
return false;
}
public int hashCode()
{
return new Long(x).hashCode()*31 + new Long(y).hashCode();
}
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 0280ffd5fb17f858f9d9e4b6c81c3461 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.io.PrintWriter;
import java.util.*;
public class Q3 {
public static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int N = in.nextInt(), M = in.nextInt();
ArrayList<String> arr = new ArrayList<>();
if(M<(N-1)){
out.println("Impossible");
}else {
for (int i = 1; i <= N && M > 0; i++) {
for (int j = i + 1; j <= N && M > 0; j++) {
if (gcd(j, i) == 1) {
arr.add(i + " " + j);
M--;
}
}
}
if (M == 0) {
out.println("Possible");
for (String i : arr)
out.println(i);
} else {
out.println("Impossible");
}
}
out.close();
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 9121f8448dc9712b133047ff1a66eb71 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.*;
import java.util.*;
import java.util.LinkedList;
import java.math.*;
import java.lang.*;
import java.util.PriorityQueue;
import static java.lang.Math.*;
public class solution implements Runnable {
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static int min(int a,int b)
{
if(a>b)
{
return b;
}
return a;
}
public static int max(int a,int b)
{
if(a>b)
{
return a;
}
return b;
}
static class pair implements Comparable<pair>
{
int x;
int y;
pair(int x,int y)
{
this.x = x;
this.y = y;
}
public int compareTo(pair p)
{
if(this.x>p.x)
{
return 1;
}
else if(this.x<p.x)
{
return -1;
}
else
{
return this.y-p.y;
}
}
}
public static int gcd(int a,int b)
{
while(b!=0)
{
int save = a%b;
a = b;
b = save;
}
return a;
}
static int max = (int)1e5+1;
public static void main(String args[]) throws Exception {
new Thread(null, new solution(),"Main",1<<26).start();
}
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int m = sc.nextInt();
boolean flag = false;
ArrayList<pair> list = new ArrayList<>();
if(m<n-1)
{
flag = false;
}
else
{
for(int i=1;i<n;i++)
{
for(int j=i+1;j<=n;j++)
{
if(gcd(j,i)==1)
{
list.add(new pair(i,j));
if(list.size()==m)
{
flag = true;
break;
}
}
}
if(flag)
{
break;
}
}
}
if(flag)
{
out.println("Possible");
for(int i=0;i<m;i++)
{
pair a = list.get(i);
out.println(a.x+" "+a.y);
}
}
else
{
out.println("Impossible");
}
out.close();
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | fe287fbdb820217ca26c7f40c78ebcff | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.util.*;
public class C1
{
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
static class pair
{
int x;
int y;
public pair(int x,int y)
{
this.x=x;
this.y=y;
}
}
public static int gcd(int a,int b)
{
if(b==0) return a;
else
return gcd(b,a%b);
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
pair[] p=new pair[m];
int k=0;
if(m<n-1)
System.out.println("Impossible");
else
{
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
if(m==0) break;
if(gcd(i,j)==1)
{
p[k++]=new pair(i,j);
m--;
}
}
if(m==0)
break;
}
if(m>0) System.out.println("Impossible");
else
{
System.out.println("Possible");
for(int i=0;i<k;i++)
{
System.out.println(p[i].x+" "+p[i].y);
}
}
}
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 754b580b2a7c7d128115aa2dd658b399 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
public class D {
public static void main(String [] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Task task = new Task();
task.solve(in, out);
out.close();
}
static class Task {
static final int LIMIT = 100005;
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int maxM = getMaxEdges(n);
if (m > maxM || m < (n - 1)) {
out.println("Impossible");
} else {
out.println("Possible");
printEdges(n, m, out);
}
}
int getMaxEdges(int n) {
int maxM = 0;
for (int u = 1; u <= n; u++) {
for (int v = u + 1; v <= n; v++) {
if (gcd(u, v) == 1) {
maxM++;
if (maxM > LIMIT) {
return maxM;
}
}
}
}
return maxM;
}
void printEdges(int n, int m, PrintWriter out) {
int cnt = 0;
for (int u = 1; u <= n; u++) {
for (int v = u + 1; v <= n; v++) {
if (gcd(u, v) == 1) {
out.println(u + " " + v);
cnt++;
if (cnt >= m) {
return;
}
}
}
}
}
static int gcd(int a, int b) {
return (a == 0) ? b : gcd(b % a, a);
}
}
/** common utils */
static class InputReader {
private static final int BUFFER_SIZE = 8192;
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), BUFFER_SIZE);
tokenizer = null;
}
private 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 nextString() {
return next();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
static class Log {
static boolean debugEnabled = true;
public static void d(Object...args) {
if (debugEnabled) {
System.out.println("D/: " + Arrays.deepToString(args));;
}
}
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 39cfa5889f367f48cf3c9a2175b8de7e | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | /*Author: Satyajeet Singh, Delhi Technological University*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.math.*;
public class Main{
/*********************************************Constants******************************************/
static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static long mod=(long)1e9+7;
static long mod1=998244353;
static boolean sieve[];
static ArrayList<Integer> primes;
static ArrayList<Long> factorial;
static HashSet<Pair> graph[];
/****************************************Solutions Begins***************************************/
public static void main (String[] args) throws Exception {
String st[]=br.readLine().split(" ");
int n=Integer.parseInt(st[0]);
int m=Integer.parseInt(st[1]);
int m1=m;
ArrayList<Integer> list=new ArrayList<>();
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
if(gcd(i,j)==1){
//out.println(i+" "+j);
list.add(i);
list.add(j);
m--;
}
if(m==0)break;
}
if(m==0)break;
}
if((list.size()/2)==m1&&m1>=n-1){
System.out.println("Possible");
for(int i=0;i<list.size();i+=2){
System.out.println(list.get(i)+" "+list.get(i+1));
}
}
else{
// debug(list.size()/2);
System.out.println("Impossible");
}
/****************************************Solutions Ends**************************************************/
out.flush();
out.close();
}
/****************************************Template Begins************************************************/
/***************************************Precision Printing**********************************************/
static void printPrecision(double d){
DecimalFormat ft = new DecimalFormat("0.00000000000000000");
out.println(ft.format(d));
}
/******************************************Graph*********************************************************/
static void Makegraph(int n){
graph=new HashSet[n];
for(int i=0;i<n;i++){
graph[i]=new HashSet<>();
}
}
static void addEdge(int a,int b,int c){
graph[a].add(new Pair(b,c));
}
/*********************************************PAIR********************************************************/
static class PairComp implements Comparator<Pair>{
public int compare(Pair p1,Pair p2){
return p2.v-p1.v;
}
}
static class Pair implements Comparable<Pair> {
int u;
int v;
int index=-1;
public Pair(int u, int v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/******************************************Long Pair*************************************************/
static class PairCompL implements Comparator<Pairl>{
public int compare(Pairl p1,Pairl p2){
if(p1.v>p2.v){
return -1;
}
else if(p1.v<p2.v){
return 1;
}
else{
return 0;
}
}
}
static class Pairl implements Comparable<Pair> {
long u;
long v;
int index=-1;
public Pairl(long u, long v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/*****************************************DEBUG***********************************************************/
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
/************************************MODULAR EXPONENTIATION***********************************************/
static long modulo(long a,long b,long c) {
long x=1;
long y=a;
while(b > 0){
if(b%2 == 1){
x=(x*y)%c;
}
y = (y*y)%c; // squaring the base
b /= 2;
}
return x%c;
}
/********************************************GCD**********************************************************/
static long gcd(long x, long y)
{
if(x==0)
return y;
if(y==0)
return x;
long r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
/******************************************SIEVE**********************************************************/
static void sieveMake(int n){
sieve=new boolean[n];
Arrays.fill(sieve,true);
sieve[0]=false;
sieve[1]=false;
for(int i=2;i*i<n;i++){
if(sieve[i]){
for(int j=i*i;j<n;j+=i){
sieve[j]=false;
}
}
}
primes=new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(sieve[i]){
primes.add(i);
}
}
}
/********************************************End***********************************************************/
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 4cdc05d8983bf20109c070a3e22a7677 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | /*Author: Satyajeet Singh, Delhi Technological University*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.math.*;
public class Main{
/*********************************************Constants******************************************/
static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static long mod=(long)1e9+7;
static long mod1=998244353;
static boolean sieve[];
static ArrayList<Integer> primes;
static ArrayList<Long> factorial;
static HashSet<Pair> graph[];
/****************************************Solutions Begins***************************************/
public static void main (String[] args) throws Exception {
String st[]=br.readLine().split(" ");
int n=Integer.parseInt(st[0]);
int m=Integer.parseInt(st[1]);
int m1=m;
ArrayList<Integer> list=new ArrayList<>();
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
if(gcd(i,j)==1){
//out.println(i+" "+j);
list.add(i);
list.add(j);
m--;
}
if(m==0)break;
}
if(m==0)break;
}
if((list.size()/2)==m1&&m1>=n-1){
out.println("Possible");
for(int i=0;i<list.size();i+=2){
out.println(list.get(i)+" "+list.get(i+1));
}
}
else{
// debug(list.size()/2);
out.println("Impossible");
}
/****************************************Solutions Ends**************************************************/
out.flush();
out.close();
}
/****************************************Template Begins************************************************/
/***************************************Precision Printing**********************************************/
static void printPrecision(double d){
DecimalFormat ft = new DecimalFormat("0.00000000000000000");
out.println(ft.format(d));
}
/******************************************Graph*********************************************************/
static void Makegraph(int n){
graph=new HashSet[n];
for(int i=0;i<n;i++){
graph[i]=new HashSet<>();
}
}
static void addEdge(int a,int b,int c){
graph[a].add(new Pair(b,c));
}
/*********************************************PAIR********************************************************/
static class PairComp implements Comparator<Pair>{
public int compare(Pair p1,Pair p2){
return p2.v-p1.v;
}
}
static class Pair implements Comparable<Pair> {
int u;
int v;
int index=-1;
public Pair(int u, int v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/******************************************Long Pair*************************************************/
static class PairCompL implements Comparator<Pairl>{
public int compare(Pairl p1,Pairl p2){
if(p1.v>p2.v){
return -1;
}
else if(p1.v<p2.v){
return 1;
}
else{
return 0;
}
}
}
static class Pairl implements Comparable<Pair> {
long u;
long v;
int index=-1;
public Pairl(long u, long v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/*****************************************DEBUG***********************************************************/
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
/************************************MODULAR EXPONENTIATION***********************************************/
static long modulo(long a,long b,long c) {
long x=1;
long y=a;
while(b > 0){
if(b%2 == 1){
x=(x*y)%c;
}
y = (y*y)%c; // squaring the base
b /= 2;
}
return x%c;
}
/********************************************GCD**********************************************************/
static long gcd(long x, long y)
{
if(x==0)
return y;
if(y==0)
return x;
long r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
/******************************************SIEVE**********************************************************/
static void sieveMake(int n){
sieve=new boolean[n];
Arrays.fill(sieve,true);
sieve[0]=false;
sieve[1]=false;
for(int i=2;i*i<n;i++){
if(sieve[i]){
for(int j=i*i;j<n;j+=i){
sieve[j]=false;
}
}
}
primes=new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(sieve[i]){
primes.add(i);
}
}
}
/********************************************End***********************************************************/
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 5e054de36b7b557995eb20f3a69c34ea | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author prakharjain
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
long gcd(long a, long b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
if (m < n - 1) {
out.println("Impossible");
return;
}
List<Pair> pairs = new ArrayList<>();
if (n <= 3200) {
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
if (pairs.size() == m)
break;
long g = gcd(i, j);
if (g == 1) {
pairs.add(new Pair<>(i, j));
}
}
}
if (pairs.size() < m) {
out.println("Impossible");
return;
} else {
print(out, pairs);
}
} else {
List<Integer> primes = prime(n);
for (int i = 0; i < primes.size(); i++) {
if (i == 0) {
for (int j = 2; j <= n; j++) {
if (pairs.size() == m)
break;
int p1 = 1;
int p2 = j;
pairs.add(new Pair(p1, p2));
}
} else {
for (int j = i + 1; j < primes.size(); j++) {
if (pairs.size() == m)
break;
int p1 = primes.get(i);
int p2 = primes.get(j);
pairs.add(new Pair(p1, p2));
}
}
}
print(out, pairs);
}
}
void print(OutputWriter out, List<Pair> pairs) {
out.println("Possible");
for (int i = 0; i < pairs.size(); i++) {
out.println(pairs.get(i).getKey() + " " + pairs.get(i).getValue());
}
}
List<Integer> prime(int n) {
boolean[] isp = new boolean[n + 1];
Arrays.fill(isp, true);
for (int i = 2; i <= n; i++) {
if (isp[i]) {
for (int j = 2; j * i <= n; j++) {
isp[i * j] = false;
}
}
}
List<Integer> primes = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (isp[i])
primes.add(i);
}
return primes;
}
class Pair<K, V> {
K k;
V v;
public Pair(K k, V v) {
this.k = k;
this.v = v;
}
K getKey() {
return k;
}
V getValue() {
return v;
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int 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;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 71a94e642a564033422c5b7fd4e4f1b8 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.DecimalFormat;
public class Main{
final long mod = (int)1e9+7, IINF = (long)1e19;
final int MAX = (int)2e5+1, MX = (int)1e7+1, INF = (int)1e9, root = 3;
DecimalFormat df = new DecimalFormat("0.0000000000000");
double eps = 1e-9, PI = 3.141592653589793238462643383279502884197169399375105820974944;
static boolean multipleTC = false, memory = false;
FastReader in;PrintWriter out;
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
else new Main().run();
}
void run() throws Exception{
in = new FastReader();
out = new PrintWriter(System.out);
for(int i = 1, T= (multipleTC)?ni():1; i<= T; i++)solve(i);
out.flush();
out.close();
}
void solve(int TC) throws Exception{
int n = ni(), m = ni();
long max = 0;
for(int i = 1; i<= n; i++)max+=phi(i);
if(max<m || m< n-1){
pn("Impossible");
return;
}
pn("Possible");
for(int i = 0; i< n-1; i++)pn("1 " + (i+2));
m-=n-1;
for(int i = 2; i<= n && m>0; i++){
for(int j = 2; j< i && m>0; j++){
if(gcd(i,j)==1){
pn(j+" " + i);
m--;
}
}
}
}
long phi (long n) {
if(n<=1)return 0;
long result = n;
for (long i=2; i*i<=n; ++i)
if (n % i == 0) {
while (n % i == 0)n /= i;
result -= result / i;
}
if (n > 1)result -= result / n;
return result;
}
int[] sort(int[] a){
if(a.length==1)return a;
int mid = a.length/2;
int[] b = sort(Arrays.copyOfRange(a,0,mid)), c = sort(Arrays.copyOfRange(a,mid,a.length));
for(int i = 0, j = 0, k = 0; i< a.length; i++){
if(j<b.length && k<c.length){
if(b[j]<c[k])a[i] = b[j++];
else a[i] = c[k++];
}else if(j<b.length)a[i] = b[j++];
else a[i] = c[k++];
}
return a;
}
long[] sort(long[] a){
if(a.length==1)return a;
int mid = a.length/2;
long[] b = sort(Arrays.copyOfRange(a,0,mid)), c = sort(Arrays.copyOfRange(a,mid,a.length));
for(int i = 0, j = 0, k = 0; i< a.length; i++){
if(j<b.length && k<c.length){
if(b[j]<c[k])a[i] = b[j++];
else a[i] = c[k++];
}else if(j<b.length)a[i] = b[j++];
else a[i] = c[k++];
}
return a;
}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bitcount(long n){return (n==0)?0:(1+bitcount(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n(){return in.next();}
String nln(){return in.nextLine();}
int ni(){return Integer.parseInt(in.next());}
long nl(){return Long.parseLong(in.next());}
double nd(){return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}catch (IOException e){
e.printStackTrace();
}
return str;
}
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 47b2e018b42c3a9b37d44413825682c7 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = (int) Long.parseLong(st.nextToken());
int m = (int) Long.parseLong(st.nextToken());
//StringTokenizer st = new StringTokenizer(br.readLine())
//bw.write(solve(n)+"\n");//adds 50 new each time
int eCount = 0;
StringBuilder graph = new StringBuilder();
out: for(int j=1;j<n;++j){
for(int k=j+1;k<=n;++k){
if(getGreatestCommonDivisor(j,k)==1){
graph.append("\n"+j+" "+k);
++eCount;
if(eCount==m)break out;
}
}
}
if(eCount ==m && m>n-2){
bw.write("Possible"+graph.toString());
}
else{
bw.write("Impossible");
}
bw.flush();
}
public static int getGreatestCommonDivisor(int a,int b){
a=Math.abs(a);
b=Math.abs(b);
if(b>a){//swap if in wrong order
int c=b;
b=a;
a=c;
}
if(b==1)return 1;
//if(b==0)return 0;//only needs to be checked once
int remainder=a-b*((int)(a/b));
if(remainder==0)return b;
return getGreatestCommonDivisor(b,remainder);
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | b61167394e2d88ae1174d1b6e96a4fb6 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.util.Scanner;
public class DRelativelyPrimeGraph {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt(), m = scan.nextInt();
int[][] ansArr = new int[m][2];
int ansCount = 0;
if (m < n - 1) {
System.out.println("Impossible");
return;
}
for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
if (gcd(i, j) == 1) {
ansArr[ansCount][0] = i;
ansArr[ansCount++][1] = j;
if (ansCount >= m) {
System.out.println("Possible");
for (int k = 0; k < ansCount; k++) {
System.out.println(ansArr[k][0] + " " + ansArr[k][1]);
}
return;
}
}
}
}
System.out.println("Impossible");
}
public static int gcd(int a, int b) {
return (a == 0) ? b : gcd(b % a, a);
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 88c2308184d4ac0fded4511df2ad37da | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution
{
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
public static int gcd(int a,int b)
{
if(b == 0)
return a;
return gcd(b,a%b);
}
public static void main(String[] args)
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
InputReader in = new InputReader(System.in);
int n = in.nextInt();
int m = in.nextInt();
ArrayList<Integer> u = new ArrayList<>();
ArrayList<Integer> v = new ArrayList<>();
int count = 0;
boolean[] vis = new boolean[n+1];
if(m < n-1)
System.out.println("Impossible");
else
{
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
if(gcd(i,j) == 1)
{
u.add(i);
v.add(j);
count++;
}
if(count == m)
break;
}
if(count == m)
break;
}
if(count != m)
System.out.println("Impossible");
else
{
System.out.println("Possible");
for(int i=0;i<u.size();i++)
{
System.out.println(u.get(i) + " " + v.get(i));
}
}
}
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 6032e7d55222f246853c9ffaa9267413 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.math.*;
import java.awt.List;
import java.io.*;
/* spar5h */
public class cf4 implements Runnable{
public static long gcd (long a, long b) {
if(b == 0)
return a;
return(gcd(b, a % b));
}
public void run() {
InputReader s = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t = 1;
outerloop:
while(t-- > 0) {
int n = s.nextInt(), m = s.nextInt();
if(m < n - 1) {
w.println("Impossible"); continue;
}
if(n <= 5000) {
ArrayList<Integer> u = new ArrayList<Integer>();
ArrayList<Integer> v = new ArrayList<Integer>();
outer:
for(int i = 1; i <= n; i++) {
for(int j = i + 1; j <= n; j++) {
if(m == 0)
break outer;
if(gcd(i, j) == 1) {
u.add(i); v.add(j); m--;
}
}
}
if(m == 0) {
w.println("Possible");
for(int i = 0; i < u.size(); i++)
w.println(u.get(i) + " " + v.get(i));
}
else
w.println("Impossible");
continue;
}
w.println("Possible");
int[] prime = new int[n + 1]; Arrays.fill(prime, 1); prime[0] = 0; prime[1] = 0;
for(int i = 2; i <= n; i++) {
if(prime[i] == 0)
continue;
for(int j = 2; (long)i * j <= n; j++)
prime[i * j] = 0;
}
ArrayList<Integer> primes = new ArrayList<Integer>();
for(int i = 2; i <= n; i++)
if(prime[i] == 1)
primes.add(i);
for(int i = 2; i <= n; i++) {
if(m == 0)
continue outerloop;
w.println(1 + " " + i); m--;
}
for(int i = 0; i < primes.size(); i++) {
for(int j = i + 1; j < primes.size(); j++) {
if(m == 0)
continue outerloop;
w.println(primes.get(i) + " " + primes.get(j)); m--;
}
}
}
w.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new cf4(),"cf4",1<<26).start();
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 87beaefd31979e6dd534390d35410c9c | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | /*
Avocado
Naked Washington
*/
import java.io.*;
import java.util.*;
public class E
{
public static void main(String args[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
if(N-1 > M)
{
System.out.println("Impossible");
System.exit(0);
}
//brute force
//fck c++ lmao
ArrayList<String> lmoa = new ArrayList<String>();
boolean ree = false;
for(int a=1; a <= N; a++)
{
if(ree)
break;
for(int b=a+1; b <= N; b++)
{
if(gcd(b, a) == 1)
lmoa.add(a+" "+b);
if(lmoa.size() >= M)
{
ree = true;
break;
}
}
}
if(ree)
{
System.out.println("Possible");
for(String a: lmoa)
System.out.println(a);
}
else
System.out.println("Impossible");
}
public static int gcd(int a, int b)
{
if(a%b == 0)
return b;
return gcd(b, a%b);
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | f742d3f429a2a5cd857a5c97fb8d7ef8 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.util.*;
public class problem1009D {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int max = console.nextInt();
int reqEdges = console.nextInt();
int[] edges = new int[2*reqEdges];
int ind = 0;
if (reqEdges<max-1) {
System.out.println("Impossible");
}
else {
outer: for (int i = 1; i<max; i++) {
for (int j = i+1; j<=max; j++) {
if (gcd(i, j) == 1) {
edges[ind] = i;
edges[ind+1] = j;
ind+=2;
reqEdges--;
if (reqEdges == 0) {
break outer;
}
}
}
}
if (reqEdges == 0) {
System.out.println("Possible");
for (int i = 0; i<edges.length/2; i++) {
System.out.print(edges[2*i]+" ");
System.out.println(edges[2*i+1]);
}
}
else {
System.out.println("Impossible");
}
}
}
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | b82fd3d547a2b46394a898c3339a469e | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author kanak893
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader fi, PrintWriter out) {
int n, m, i, j, k;
n = fi.nextInt();
m = fi.nextInt();
HashSet<Integer>[] adj = new HashSet[n + 1];
for (i = 0; i <= n; i++) {
adj[i] = new HashSet<>();
}
int total = 0;
if (m < n - 1) {
out.println("Impossible");
return;
}
StringBuilder sb = new StringBuilder("");
for (i = 1; i <= n; i++) {
for (j = i + 1; j <= n; j++) {
if (gcd(i, j) == 1) {
total++;
sb.append(i + " " + j + "\n");
}
if (total == m) {
break;
}
}
if (total == m) break;
}
if (total < m) {
out.println("Impossible");
} else {
out.println("Possible");
out.println(sb.toString());
}
}
static int gcd(int a, int b) {
if (b == 0) {
return a;
} else return gcd(b, a % b);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 76ed17a99d365ae524b4b949a0b0fb90 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int m=s.nextInt();
ArrayList<pair> list=new ArrayList<>();
int count=0;
for(int i=1;i<n+1;i++)
{
for(int j=i+1;j<n+1;j++)
{
if(gcd(i,j)==1)
{
count++;
pair p=new pair(i,j);
list.add(p);
}
if(count==m)
{
break;
}
}
if(count==m)
break;
}
if(count!=m||m<n-1)
{
System.out.println("Impossible");
}
else
{
System.out.println("Possible");
for(int i=0;i<m;i++)
{
System.out.println(list.get(i).left+" "+list.get(i).right);
}
}
}
public static int gcd(int a,int b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
}
class pair
{
int left;
int right;
public pair(int left,int right)
{
this.left=left;
this.right=right;
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | e51237554ca5d892abcabdfb221ace0e | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
public class EDU_47_D {
static final int TEST_CASES = 2;
public static void main(String[] args) {
//test(TEST_CASES);
Scanner sc = new Scanner(new BufferedReader(new
InputStreamReader(System.in)));
solve(sc);
sc.close();
}
static void test(int T) {
for (int i = 0; i < T; ++i) {
System.out.println(String.format("*****Case #%d*****", i));
try {
Scanner sc = new Scanner(new FileReader(String.format("EDU_43/%d.in", i)));
solve(sc);
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
static void solve(Scanner sc) {
// n > 150 : always true
// n < 150 : brute force test
int n = sc.nextInt();
int m = sc.nextInt();
// Can't be connected
if(n-1 > m) {
System.out.println("Impossible");
}
else if(n > 1000) {
System.out.println("Possible");
outer: for(int i = 1; i <= n; ++i) {
for(int j = i+1; j <= n; ++j) {
if(m == 0)
break outer;
if(gcd(j,i) == 1) {
System.out.println(i + " " + j);
--m;
}
}
}
} else {
long count = 0;
for(int i = 1; i <= n; ++i) {
for(int j = i+1; j <= n; ++j) {
if(gcd(j,i) == 1)
++count;
}
}
if(count >= m) {
System.out.println("Possible");
outer: for(int i = 1; i <= n; ++i) {
for(int j = i+1; j <= n; ++j) {
if(m == 0)
break outer;
if(gcd(j,i) == 1) {
System.out.println(i + " " + j);
--m;
}
}
}
} else {
System.out.println("Impossible");
}
}
}
static int gcd(int a, int b) {
if(b == 0)
return a;
return gcd(b,a%b);
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | a8e8fdbb958a14ab93916b60756d94d7 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
import static java.lang.Integer.*;
import static java.lang.Double.*;
import java.lang.Math.*;
public class relatively_prime_graph {
public static void main(String[] args) throws Exception {
new relatively_prime_graph().run();
}
public static FastIO file = new FastIO();
public void run() throws Exception {
long n = file.nextLong(); int m = file.nextInt();
if (m < n - 1) {
println("Impossible");
}
else if (m > n * (n - 1) / 2) {
println("Impossible");
}
else {
Pair<Integer, Integer> ret[] = new Pair[m];
int ind = 0;
outer: for (int i = 1; i <= n; i++) {
for (int j = i + 1; j <= n; j++) {
if (ind == m) break outer;
if (gcd(i, j) == 1) {
ret[ind++] = new Pair<Integer, Integer>(i, j);
}
}
}
if (ind == m) {
println("Possible");
for (int i = 0; i < m; i++) {
println(ret[i].fi + " " + ret[i].se);
}
}
else {
println("Impossible");
}
}
file.out.flush();
file.out.close();
}
public static long mod(long n, long mod) {
return (n % mod + mod) % mod;
}
public static long pow(long n, long p, long mod) {
if (p == 0L)
return mod(1L, mod);
if (p == 1L)
return mod(n, mod);
long t = mod(pow(n, p >> 1, mod), mod);
if (p % 2L == 0L) {
return mod(t * t, mod);
}
t = mod(t * t, mod);
t = mod(t * n, mod);
return mod(t, mod);
}
public static long pow(long n, long p) {
return pow(n, p, Long.MAX_VALUE);
}
public static long gcd(long x, long y) {
if (x == 0)
return y;
return gcd(y % x, x);
}
public static long lcm(long x, long y) {
return x / gcd(x, y) * y;
}
public static boolean isPrime(int n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static class Pair<A, B> implements Comparable {
public A fi;
public B se;
public Pair(A fi, B se) {
this.fi = fi;
this.se = se;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair<?, ?> p = (Pair<?, ?>) o;
if (!fi.equals(p.fi))
return false;
return se.equals(p.se);
}
@Override
public int hashCode() {
return 31 * fi.hashCode() + se.hashCode();
}
@Override
public String toString() {
return fi.toString() + " " + se.toString();
}
public static <A, B> Pair<A, B> of(A a, B b) {
return new Pair<A, B>(a, b);
}
public int compareTo(Object o) {
Pair<?, ?> p = (Pair<?, ?>) o;
if (fi.equals(p.fi))
return ((Comparable) se).compareTo(p.se);
return ((Comparable) fi).compareTo(p.fi);
}
}
public static void print(Object o) {
file.out.print(o);
}
public static void println(Object o) {
file.out.println(o);
}
public static void printf(String s, Object... o) {
file.out.printf(s, o);
}
public static class FastIO {
BufferedReader br;
StringTokenizer st;
PrintWriter out;
public FastIO() {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
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;
}
void print(Object o) {
out.print(o);
}
void println(Object o) {
out.println(o);
}
void printf(String s, Object... o) {
out.printf(s, o);
}
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | ef06581b9ce6d09d83a154237ad9cc9b | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class RelativelyPrimeGraph {
private static ArrayList<Integer[]> edges;
private static int e, v;
private static int gcd(int a, int b) {
if (b == 0) return a;
else return gcd(b, a % b);
}
private static void findEdges(int e) {
for (int i = 1; i < v; i++) {
edges.add(new Integer[] {i, i + 1});
if (--e == 0) return;
}
for (int i = 1; i < v; i++) {
for (int j = i + 2; j <= v; j++) {
if (gcd(i, j) == 1) {
edges.add(new Integer[]{i, j});
if (--e == 0) return;
}
}
}
}
private static void findAnswer() {
if (e < v - 1) {
System.out.println("Impossible");
return;
}
findEdges(e);
if (edges.size() < e) {
System.out.println("Impossible");
return;
}
System.out.println("Possible");
for (Integer[] pair: edges) System.out.println(pair[0] + " " + pair[1]);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
v = scanner.nextInt();
e = scanner.nextInt();
edges = new ArrayList<>(e);
findAnswer();
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 7592d09c6b24ad4dd0ea12f5a5c3d03b | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class TaskD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
List<Edge> E = new ArrayList<Edge>();
for(int i = 1; i <= n; i++) {
for(int j = i + 1; j <= n; j++) {
if(gcd(i, j) == 1) {
E.add(new Edge(i, j));
}
}
if(m <= E.size()) {
break;
}
}
if(m < n - 1) {
System.out.println("Impossible");
}else if(m > E.size()) {
System.out.println("Impossible");
}else {
System.out.println("Possible");
Iterator<Edge> iter = E.iterator();
while(iter.hasNext()) {
if(m <= 0) {
break;
}
Edge e = iter.next();
System.out.println(e.u + " " + e.v);
m--;
}
}
}
private static int gcd(int x, int y) {
if( x < y) {
return gcd(y, x);
}
if(y == 0) {
return x;
}
return gcd(y, x % y);
}
}
class Edge{
int u;
int v;
Edge(int u, int v){
this.u = u;
this.v = v;
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 16d1704b7237188a4879d6bb2ee4a68e | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes |
import javax.print.DocFlavor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.management.MemoryType;
import java.net.Inet4Address;
import java.nio.charset.IllegalCharsetNameException;
import java.time.temporal.Temporal;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
public class Main{
public static void main(String[] args) throws IOException{
Reader.init(System.in);
// int t =Reader.nextInt();
int t = 1;
int i = 1;
while (t-->0){
// System.out.print("Case #" + i + ": ");
solve();
i++;
}
}
static TreeSet<Integer>[] graph;
static HashMap<String, Integer> map;
static boolean[] v;
static int[] p;
static int ans = 1;
static void solve() throws IOException{
int n = Reader.nextInt();
int m = Reader.nextInt();
if (m < n-1){
System.out.println("Impossible");
return;
}
int cnt = 0;
int f= 0;
for (int i =1 ; i <=n ; i++){
for (int j = 1 ; j<= n ; j++){
if (i < j){
if (gcd((long)i,(long)j)==1){
cnt++;
if (cnt==m){
System.out.println("Possible");
f = 1;
fun(n,m);
return;
}
}
}
}
}
System.out.println("Impossible");
}
static void fun(int n , int m){
int cnt = 0;
for (int i =1 ; i <=n ; i++){
for (int j = 1 ; j<= n ; j++){
if (i < j){
if (gcd((long)i,(long)j)==1){
cnt++;
System.out.println(i + " " + j);
if (cnt==m){
return;
}
}
}
}
}
}
// static void dfs(int cur, int bit){
// if (v[cur]){
// return;
// }
// v[cur] = true;
// p[cur] = bit;
// Iterator<Integer> i = graph[cur].iterator();
// while (i.hasNext()){
// int next = i.next();
// dfs(next,bit^1);
// }
// }
//
// static int[] bfs(LinkedList<Integer>[] input,int source,int n){
// LinkedList<Integer>[] graph = input;
// int[] d1 = new int[n+1];
// boolean[] v = new boolean[n+1];
// Arrays.fill(d1,-1);
// Deque<Integer> q = new LinkedList<>();
// d1[source] = 0;
// q.addLast(source);
// v[source] = true;
// while (q.isEmpty()==false){
// int s = q.removeFirst();
// Iterator<Integer> i = graph[s].iterator();
// while (i.hasNext()){
// int next = i.next();
// if (!v[next]){
// v[next] = true;
// q.addLast(next);
// d1[next] = d1[s] + 1;
// }
// }
// }
// return d1;
// }
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
public static int stringCompare(String str1, String str2)
{
int l1 = str1.length();
int l2 = str2.length();
int lmin = Math.min(l1, l2);
for (int i = 0; i < lmin; i++) {
int str1_ch = (int)str1.charAt(i);
int str2_ch = (int)str2.charAt(i);
if (str1_ch != str2_ch) {
return str1_ch - str2_ch;
}
}
if (l1 != l2) {
return l1 - l2;
}
else {
return 0;
}
}
static int next(long[] arr, long target)
{
int start = 0, end = arr.length - 1;
int ans = -1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] <= target) {
start = mid + 1;
}
else {
ans = mid;
end = mid - 1;
}
}
return ans;
}
// static int find(int x) {
// return parent[x] == x ? x : (parent[x] = find(parent[x]));
// }
// static boolean merge(int x, int y) {
// x = find(x);
// y = find(y);
// if (x==y){
// return false;
// }
// parent[x] = y;
// return true;
// }
public static void sortbyColumn(int arr[][], int col)
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
});
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
class Pair{
int a;
int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
}
class MergeSort
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method
}
class Node implements Comparable<Node>{
int a;
int b;
Node (int a , int b){
this.a = a;
this.b = b;
}
public int compareTo(Node o) {
if ((this.a%2) == (o.a%2)){
return (this.b - o.b);
}
else{
return this.a - o.a;
}
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 180c7db72cd79a44af2b70b5ddc93d6f | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
public int i(){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;}
public double d() throws IOException {return Double.parseDouble(s()) ;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;}
}
// |----| /\ | | ----- |
// | / / \ | | | |
// |--/ /----\ |----| | |
// | \ / \ | | | |
// | \ / \ | | ----- -------
static class pair
{
int a,b;
public pair(int a,int b)
{
this.a=a;
this.b=b;
}
}
public static int GCD(int a, int b)
{
if (b==0)
return a;
return GCD(b,a%b);
}
public static void main(String[] args)throws IOException
{
PrintWriter out= new PrintWriter(System.out);
Reader sc=new Reader();
int n=sc.i();
int m=sc.i();
ArrayList<pair> al=new ArrayList<>();
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
if(GCD(i,j)==1)
al.add(new pair(i,j));
if(al.size()>=m)
break;
}
if(al.size()<m||m<n-1)
out.println("Impossible");
else
{
out.println("Possible");
for(int i=0;i<m;i++)
out.println(al.get(i).a+" "+al.get(i).b);
}
out.flush();
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 544a351d69dd28e108937e53b344045e | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
public class A {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int m = ni();
ArrayList<String> ls = new ArrayList<>();
if(m<n-1){
out.println("Impossible");
}else{
int cur = 1;
boolean visited[] = new boolean[n+1];
while(m>0 && cur <=n){
for(int i=cur+1;i<=n;i++){
if(m<=0) break;
if(gcd(cur, i)==1){
String s = Integer.toString(cur)+" "+Integer.toString(i);
ls.add(s);
visited[cur] = true; visited[i] = true;
m--;
}
}
cur++;
}
boolean flag = false;
for(int i=1;i<=n;i++) if(!visited[i]) flag = true;
if(m>0 || flag){
out.println("Impossible");
}else{
out.println("Possible");
for(String s: ls){
out.println(s);
}
}
}
}
static int gcd(int a, int b){
if(b==0) return a;
return gcd(b, a%b);
}
void run() throws Exception
{
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new A().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 4368c3237264534ca4e1c7f884b05a82 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
public class A {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int m = ni();
ArrayList<String> ls = new ArrayList<>();
if(m<n-1){
out.println("Impossible");
}else{
int cur = 1;
while(m>0 && cur <=n){
for(int i=cur+1;i<=n;i++){
if(m<=0) break;
if(gcd(cur, i)==1){
String s = Integer.toString(cur)+" "+Integer.toString(i);
ls.add(s);
m--;
}
}
cur++;
}
if(m>0){
out.println("Impossible");
}else{
out.println("Possible");
for(String s: ls){
out.println(s);
}
}
}
}
static int gcd(int a, int b){
if(b==0) return a;
return gcd(b, a%b);
}
void run() throws Exception
{
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new A().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | f9337ba1aca87329fe6c0c002cd4ebb8 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.HashMap;
public class templ implements Runnable {
class pair
{
int v,val;
pair(int f,int s)
{
v=f;
val=s;
}
}
public static ArrayList<Integer> g[]=new ArrayList[1000000];
public static int vis[]=new int[1000000];
public static long M=1000000007;
long a[]=new long[1000000];
long b[]=new long[1000000];
int o=0;
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid-1, x);
return binarySearch(arr, mid+1, r, x);
}
return -1;
}
void merge1(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i]<=R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void sort1(int arr[], int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort1(arr, l, m);
sort1(arr , m+1, r);
merge1(arr, l, m, r);
}
}
void merge3(int arr[],int arr1[],int arr2[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
int L1[]=new int[n1];
int R1[]=new int[n2];
int L2[]=new int[n1];
int R2[]=new int[n2];
//long L3[]=new long[n1];
//long R3[]=new long[n2];
for (int i=0; i<n1; ++i)
{
L[i] = arr[l + i];
L1[i]=arr1[l+i];
L2[i]=arr2[l+i];
//L3[i]=arr3[l+i];
}
for (int j=0; j<n2; ++j)
{
R[j] = arr[m + 1+ j];
R1[j]=arr1[m+1+j];
R2[j]=arr2[m+1+j];
//R3[j]=arr3[m+1+j];
}
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
arr1[k]=L1[i];
arr2[k]=L2[i];
//arr3[k]=L3[i];
i++;
}
else
{
arr[k] = R[j];
arr1[k]=R1[j];
arr2[k]=R2[j];
//arr3[k]=R3[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
arr1[k]=L1[i];
arr2[k]=L2[i];
//arr3[k]=L3[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
arr1[k]=R1[j];
arr2[k]=R2[j];
//arr3[k]=R3[j];
j++;
k++;
}
}
void sort3(int arr[],int arr1[],int arr2[], int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort3(arr,arr1,arr2, l, m);
sort3(arr ,arr1,arr2, m+1, r);
merge3(arr,arr1,arr2,l, m, r);
}
}
void merge2(long arr[],long arr1[],int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
long L[] = new long [n1];
long R[] = new long [n2];
long L1[]=new long[n1];
long R1[]=new long[n2];
for (int i=0; i<n1; ++i)
{
L[i] = arr[l + i];
L1[i]=arr1[l+i];
}
for (int j=0; j<n2; ++j)
{
R[j] = arr[m + 1+ j];
R1[j]=arr1[m+1+j];
}
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
arr1[k]=L1[i];
i++;
}
else
{
arr[k] = R[j];
arr1[k]=R1[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
arr1[k]=L1[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
arr1[k]=R1[j];
j++;
k++;
}
}
void sort2(long arr[],long arr1[],int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort2(arr,arr1, l, m);
sort2(arr ,arr1, m+1, r);
merge2(arr,arr1,l, m, r);
}
}
void merge4(int arr[],int arr1[],int arr2[],int arr3[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
int L1[]=new int[n1];
int R1[]=new int[n2];
int L2[]=new int[n1];
int R2[]=new int[n2];
int L3[]=new int[n1];
int R3[]=new int[n2];
for (int i=0; i<n1; ++i)
{
L[i] = arr[l + i];
L1[i]=arr1[l+i];
L2[i]=arr2[l+i];
L3[i]=arr3[l+i];
}
for (int j=0; j<n2; ++j)
{
R[j] = arr[m + 1+ j];
R1[j]=arr1[m+1+j];
R2[j]=arr2[m+1+j];
R3[j]=arr3[m+1+j];
}
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
arr1[k]=L1[i];
arr2[k]=L2[i];
arr3[k]=L3[i];
i++;
}
else
{
arr[k] = R[j];
arr1[k]=R1[j];
arr2[k]=R2[j];
arr3[k]=R3[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
arr1[k]=L1[i];
arr2[k]=L2[i];
arr3[k]=L3[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
arr1[k]=R1[j];
arr2[k]=R2[j];
arr3[k]=R3[j];
j++;
k++;
}
}
void sort4(int arr[],int arr1[],int arr2[],int arr3[], int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort4(arr,arr1,arr2,arr3, l, m);
sort4(arr ,arr1,arr2,arr3, m+1, r);
merge4(arr,arr1,arr2,arr3,l, m, r);
}
}
public int justsmall(int a[],int l,int r,int x)
{
int p=-1;
while(l<=r)
{
int mid=(l+r)/2;
if(a[mid]<=x)
{
p=mid;
l=mid+1;
}
else
r=mid-1;
}
return p;
}
public int justlarge(int a[],int l,int r,int x)
{
int p=0;
while(l<=r)
{
int mid=(l+r)/2;
if(a[mid]<=x)
{
l=mid+1;
}
else
{
p=a[mid];
r = mid - 1;
}
}
return p;
}
long gcd(long x,long y)
{
if(x%y==0)
return y;
else
return(gcd(y,x%y));
}
long fact(long n)
{
long ans=1;
for(int i=1;i<=n;i++)
ans*=i;
return ans;
}
void farey(int n)
{
double x1 = 0, y1 = 1, x2 = 1, y2 = n;
a[o]=1;
b[o]=n;
o++;
double x, y = 0;
while (y != 1.0) {
x = Math.floor((y1 + n) / y2) * x2 - x1;
y = Math.floor((y1 + n) / y2) * y2 - y1;
if((long)x!=(long)y)
{
a[o]=(long)x;
b[o]=(long)y;
o++;
if(o>100007)
break;
}
x1 = x2;
x2 = x;
y1 = y2;
y2 = y;
}
}
public static void main(String args[])throws Exception
{
new Thread(null,new templ(),"templ",1<<26).start();
}
public void run() {
try
{
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n=in.ni();
int m=in.ni();
farey(n);
if(o<m||n==1||m<n-1)
out.println("Impossible");
else
{
out.println("Possible");
for(int i=2;i<=n;i++)
out.println("1 "+i);
m-=(n-1);
for(int i=0;i<o;i++)
{
if(m==0)
break;
if(a[i]!=1)
{
out.println(a[i] + " " + b[i]);
m--;
}
}
}
out.close();
}
catch(Exception e){
return;
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nl() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 634f2d43e3a7feb728bb2134795241a9 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.*;
public class Main
{
static int gcd(int a,int b){
if(a==0)
return b;
else
return gcd(b%a,a);
}
public static void main(String[] args)throws IOException
{
FastReader in=new FastReader(System.in);
StringBuffer st=new StringBuffer();
int n=in.nextInt();
int m=in.nextInt();
if(m<n-1)
System.out.println("Impossible");
else{
int c=0;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(c==m)
break;
if(gcd(i+1,j+1)==1){
st.append((j+1)+" "+(i+1)+"\n");
c++;
}
}
}
if(c!=m)
System.out.println("Impossible");
else{
System.out.println("Possible");
System.out.print(st);
}
}
}
static class FastReader{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is) {
in = is;
}
int scan() throws IOException {
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException {
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException {
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | df866ad0c0fb8274ce11c4adaae15d95 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class test{
static HashSet<Integer> adj[];
static int n,m;
public static void main(String[] args)throws Exception{
n = nextInt();
m = nextInt();
if(m<n-1){
System.out.println("Impossible");
return;
}
adj = new HashSet[n+1];
for(int i=0;i<=n;i++)
adj[i] = new HashSet<Integer>();
m-=n-1;
for(int i=n;i>0;i--) {
if(isPrime(i)) {
for(int j=1;j<=n;j++) {
if(i==j)
continue;
adj[i].add(j);
}
break;
}
}
// Pair[] q = new Pair[m];
// int f=0;
// int r=0;
// if(addEdge(2,1))
// q[r++]=new Pair(2,1);
// if(addEdge(3,1))
// q[r++]=new Pair(3,1);
// while(m>0 && f<r){
// int a = q[f].n;
// int b = q[f++].m;
// int u = 2*a-b;
// int v = a;
// if(addEdge(u,v))
// q[r++]=new Pair(u,v);
// u = 2*a+b;
// if(addEdge(u,v))
// q[r++]=new Pair(u,v);
// u = a+2*b;
// v = b;
// if(addEdge(u,v))
// q[r++]=new Pair(u,v);
// }
int a=0,b=1,c=1,d=n;
addEdge(c,d);
while(c<=n && m>0) {
int k = (n+b)/d;
int na = c;
int nb = d;
int nc = k*c-a;
int nd = k*d-b;
addEdge(nc,nd);
a=na;
b=nb;
c=nc;
d=nd;
}
if(m==0) {
PrintWriter pw = new PrintWriter(System.out);
pw.println("Possible");
for(int i=1;i<=n;i++)
for(int j:adj[i])
pw.println(i+" "+j);
pw.flush();
} else {
System.out.println("Impossible");
}
}
static boolean addEdge(int u,int v) {
if(u==v)
return false;
if(u<=0 || v<=0 || u>n || v>n)
return false;
if(m<=0)
return false;
if(adj[u].contains(v) || adj[v].contains(u))
return false;
adj[u].add(v);
m--;
return true;
}
static class Pair {
int n, m;
Pair(int a,int b) {
n=a;
m=b;
}
}
static long gcd(long a,long b){
if(b==0)
return a;
return gcd(b,a%b);
}
static boolean isPrime(int n){
if(n<2)
return false;
int m = (int)Math.sqrt(n);
for(int i=2;i<=m;i++){
if(n%i==0)
return false;
}
return true;
}
static int nextInt()throws IOException{
InputStream in=System.in;
int ans=0;
boolean flag=true;
byte b=0;
boolean neg=false;
while ((b>47 && b<58) || flag){
if(b==45)
neg=true;
if(b>=48 && b<58){
ans=ans*10+(b-48);
flag=false;
}
b=(byte)in.read();
}
if(neg)
return -ans;
return ans;
}
static int gcd(int a,int b){
if(b==0)
return a;
return gcd(b,a%b);
}
static long nextLong()throws IOException{
InputStream in=System.in;
long ans=0;
boolean flag=true;
byte b=0;
while ((b>47 && b<58) || flag){
if(b>=48 && b<58){
ans=ans*10+(b-48);
flag=false;
}
b=(byte)in.read();
}
return ans;
}
static String next()throws Exception{
StringBuilder sb=new StringBuilder(1<<16);
InputStream in=System.in;
byte b=0;
do{
if(!isWhiteSpace(b))
sb.append((char)b);
b=(byte)in.read();
}while(!isWhiteSpace(b) || sb.length()==0);
return sb.toString();
}
static boolean isWhiteSpace(byte b){
char ch=(char)b;
return ch=='\0' || ch==' ' || ch=='\n';
}
} | Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 6c810982cc31b77140f23b1a66d4f493 | train_000.jsonl | 1531578900 | Let's call an undirected graph $$$G = (V, E)$$$ relatively prime if and only if for each edge $$$(v, u) \in E$$$ $$$GCD(v, u) = 1$$$ (the greatest common divisor of $$$v$$$ and $$$u$$$ is $$$1$$$). If there is no edge between some pair of vertices $$$v$$$ and $$$u$$$ then the value of $$$GCD(v, u)$$$ doesn't matter. The vertices are numbered from $$$1$$$ to $$$|V|$$$.Construct a relatively prime graph with $$$n$$$ vertices and $$$m$$$ edges such that it is connected and it contains neither self-loops nor multiple edges.If there exists no valid graph with the given number of vertices and edges then output "Impossible".If there are multiple answers then print any of them. | 256 megabytes | import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class q4 {
private static int gcd(int a, int b){
if(b==0){
return a;
}else{
return gcd(b, a%b);
}
}
public static void main(String[] args){
int n, m;
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
int minimum = n-1;
if(m<minimum){
System.out.println("Impossible");
return;
}
int count = 0;
List<String> printString = new ArrayList<>();
for(int i=1; i<=n; i++){
for(int j=i+1; j<=n; j++){
if(gcd(i, j)==1){
printString.add(i+" "+j);
count++;
if(count>=m){
break;
}
}
}
if(count>=m){
break;
}
}
if(count<m){
System.out.println("Impossible");
return;
}
System.out.println("Possible");
for(int k=0; k<printString.size(); k++){
System.out.println(printString.get(k));
}
}
}
| Java | ["5 6", "6 12"] | 2 seconds | ["Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4", "Impossible"] | NoteHere is the representation of the graph from the first example: | Java 8 | standard input | [
"greedy",
"graphs",
"constructive algorithms",
"math",
"brute force"
] | 0ab1b97a8d2e0290cda31a3918ff86a4 | The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of vertices and the number of edges. | 1,700 | If there exists no valid graph with the given number of vertices and edges then output "Impossible". Otherwise print the answer in the following format: The first line should contain the word "Possible". The $$$i$$$-th of the next $$$m$$$ lines should contain the $$$i$$$-th edge $$$(v_i, u_i)$$$ of the resulting graph ($$$1 \le v_i, u_i \le n, v_i \neq u_i$$$). For each pair $$$(v, u)$$$ there can be no more pairs $$$(v, u)$$$ or $$$(u, v)$$$. The vertices are numbered from $$$1$$$ to $$$n$$$. If there are multiple answers then print any of them. | standard output | |
PASSED | 191908ac989bb4399549d838c5602eda | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | //package com.company;
import java.io.*;
import java.util.*;
//@author Maurice Saldivar
public class Main
{
private static class Cost implements Comparable<Cost>
{
int cost;
int position;
public Cost(int cost, int position)
{
this.cost = cost;
this.position = position;
}
@Override
public int compareTo(Cost o) {
return this.cost > o.cost ? 1 : -1;
}
}
public static void main(String[] args) throws IOException{
BufferedReader aReader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter aWriter = new PrintWriter(System.out, true);
StringBuilder tokens = new StringBuilder(aReader.readLine());
long isBalanced = 0;
long score = 0;
//queue is used to make symbol table to make sure everything matches
Queue<Cost> balanceTable = new PriorityQueue<Cost>();
String prices[] = new String[2];
for (int i = 0; i < tokens.length(); i++)
{
if(tokens.charAt(i) == '(')
isBalanced++;
else if(tokens.charAt(i) == ')')
isBalanced--;
else if(tokens.charAt(i) == '?')
{
prices = aReader.readLine().split(" ");
tokens.setCharAt(i, ')');
int val = Integer.parseInt(prices[0]) - Integer.parseInt(prices[1]);
balanceTable.add(new Cost(val, i));
score += Integer.parseInt(prices[1]);
isBalanced--;
}
if(!balanceTable.isEmpty() && isBalanced == -1)
{
Cost temp = balanceTable.poll();
tokens.setCharAt(temp.position, '(');
score += temp.cost;
isBalanced += 2;
}else if(isBalanced < -1)
break;
}
if(isBalanced == 0)
{
aWriter.println(score);
aWriter.println(tokens);
}else
aWriter.println(-1);
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | 5af775d3812e6c4c4db743c2dc2610e0 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Bracketsolver
{
public class questionMark implements Comparable<questionMark>
{
int index;
int savings;
questionMark(int _lhs, int _rhs, int _index)
{
index = _index;
savings = _rhs - _lhs; // will be negative if rhs is smaller
}
@Override
public int compareTo(questionMark rhs)
{
//-1 to make priority queue largest first
return -1* Integer.compare(savings, rhs.savings);
}
}
public static void main(String[] args)
{
Bracketsolver solver = new Bracketsolver();
Scanner in = new Scanner(System.in);
char[] orgSeq = in.nextLine().toCharArray();
char[] newSeq = orgSeq.clone();
PriorityQueue<questionMark> queueOfBrackets = new PriorityQueue<questionMark>();
int bracketsNeedClosing = 0;
int lhsCost, rhsCost;
long finalCost = 0;
questionMark top;
for (int i = 0; i < orgSeq.length; ++i)
{
if (orgSeq[i] == '(')
{
++bracketsNeedClosing;
}
else if (orgSeq[i] == ')')
{
--bracketsNeedClosing;
}
else if (orgSeq[i] == '?')
{
lhsCost = in.nextInt();
rhsCost = in.nextInt();
queueOfBrackets.add(solver.new questionMark(lhsCost, rhsCost, i));
newSeq[i] = ')';
--bracketsNeedClosing;
finalCost += rhsCost;
}
// else if(orgSeq[i] == '?' && bracketsNeedClosing == 0)
// {
// lhsCost = in.nextInt();
// rhsCost = in.nextInt();
// newSeq[i] = '(';
// ++bracketsNeedClosing;
// finalCost += lhsCost;
// }
if (bracketsNeedClosing == -1 && queueOfBrackets.size() > 0)
{
top = queueOfBrackets.poll();
newSeq[top.index] = '(';
finalCost -= top.savings; //savings could be negative if it is a bad choice
bracketsNeedClosing = 1;
}
else if(bracketsNeedClosing == -1 && queueOfBrackets.size() ==0)
{
break;
}
}
if (bracketsNeedClosing != 0)
{
System.out.println(-1);
}
else
{
System.out.println(finalCost);
System.out.println(newSeq);
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | 7b821ba078d06c0b34fd897ab6b74f5a | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class LeastCostBracketSequence implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
private class Wildcard implements Comparable<Wildcard> {
private int idx;
private long diff;
private Wildcard(int idx, long diff) {
this.idx = idx;
this.diff = diff;
}
@Override
public int compareTo(Wildcard o) {
return Long.compare(this.diff, o.diff);
}
}
public void solve() {
char[] x = in.next().toCharArray();
PriorityQueue<Wildcard> queue = new PriorityQueue<>();
int n = x.length, cost = 0;
long result = 0;
for (int i = 0; i < n; i++) {
if (x[i] == '(') {
cost++;
} else if (x[i] == ')') {
cost--;
} else {
long left = in.ni(), right = in.ni();
queue.offer(new Wildcard(i, left - right));
result += right;
x[i] = ')';
cost--;
}
if (cost < 0) {
if (queue.isEmpty()) {
out.println(-1);
return;
} else {
Wildcard top = queue.poll();
x[top.idx] = '(';
result += top.diff;
cost += 2;
}
}
}
if (cost > 0) {
out.println(-1);
} else {
out.println(result);
for (char c : x) out.print(c);
}
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
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 ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (LeastCostBracketSequence instance = new LeastCostBracketSequence()) {
instance.solve();
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | d9767a13030edbbd8c243503ce45c8a0 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.util.*;
public class cf3d {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char[] v = in.next().trim().toCharArray();
PriorityQueue<Change> pq = new PriorityQueue<Change>();
int cnt = 0;
long cost = 0;
for(int i=0; i<v.length; i++) {
if(v[i] != '?') {
if(v[i] == '(')
cnt++;
else
cnt--;
}
else {
int left = in.nextInt();
int right = in.nextInt();
cost += right;
v[i] = ')';
cnt--;
pq.add(new Change(left-right,i));
}
if(cnt < 0) {
if(pq.isEmpty()) break;
Change c = pq.poll();
cost += c.cost;
v[c.pos] = '(';
cnt += 2;
}
}
if(cnt != 0)
System.out.println("-1");
else
System.out.println(cost + "\n" + String.valueOf(v));
}
static class Change implements Comparable<Change> {
int cost, pos;
Change(int a, int b) {
cost = a;
pos = b;
}
public int compareTo(Change c) {
return cost-c.cost;
}
}
} | Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | fd2cec3304abced38dfe115c32e56ce7 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
public class Main{
public static class Position implements Comparable<Position>{
char character;
int difference;
boolean changeable;
int location;
Position(char newCharacter, int newDif, boolean newChangeable, int newLocation){
this.character = newCharacter;
this.difference = newDif; //how much we'll gain by changing from rp to lp
this.changeable = newChangeable; //whether we are allowed to alter this
this.location = newLocation;
}
@Override
public int compareTo(Position P){
return P.difference - this.difference;
}
}
public static int findBiggestDifference(int stopPosition){
int tempBiggestDif = positionList.get(changeableIndices.get(0)).difference;
int biggestLocation = changeableIndices.get(0);
int changeableIndexLocation = 0; //set to location of first changeable
if(changeableIndices.get(0)>stopPosition) return -1; //If we need to change something but aren't able to
for(int i=0; changeableIndices.size()>i && changeableIndices.get(i)<=stopPosition; i++){
if(positionList.get(changeableIndices.get(i)).difference>tempBiggestDif){
tempBiggestDif = positionList.get(changeableIndices.get(i)).difference;
biggestLocation = changeableIndices.get(i);
changeableIndexLocation = i;
}
}
//once something has been changed to a left, take it out
changeableIndices.remove(changeableIndexLocation);
return biggestLocation;
}
public static String inputString = null;
public static ArrayList<Position> positionList = new ArrayList<Position>();
public static ArrayList<Integer> changeableIndices = new ArrayList<Integer>();
public static int leftPNum = 0;
public static int rightPNum = 0;
public static Long totalCost = 0L;
public static PriorityQueue<Position> maxHeap = new PriorityQueue<Position>();
public static void main(String[] args){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String startString = null;
char[] inputArray;
String[] parsedString;
boolean illegal = false;
int replacePosition = 0;
try {
inputString = in.readLine();
} catch (Exception e) {
}
inputArray = inputString.toCharArray();
for(int i=0; i<inputArray.length; i++){
if(inputArray[i]=='('){
//positionList.add(new Position(inputArray[i],0,false, i));
leftPNum++;
}
else if(inputArray[i]==')'){
//positionList.add(new Position(inputArray[i],0, false, i));
rightPNum++;
}
else{
try {
startString = in.readLine();
} catch (Exception e) {
}
parsedString = startString.split(" ");
//we are initially going to assume that the best circumstance in all right parens
//positionList.add(new Position(')',Integer.parseInt(parsedString[1])-Integer.parseInt(parsedString[0]), true, i));
maxHeap.offer(new Position(')',Integer.parseInt(parsedString[1])-Integer.parseInt(parsedString[0]), true, i));
inputArray[i]=')';
rightPNum++;
totalCost += Long.parseLong(parsedString[1]);
//changeableIndices.add(i); //put this index in our tracking array
}
if(rightPNum - leftPNum > 0){
if(maxHeap.size()==0){ //if we need to replace something but there is nothing to replace, ie ())?
illegal = true;
break;
}
Position replacePos = maxHeap.poll();
inputArray[replacePos.location]='(';
totalCost -= replacePos.difference;
leftPNum++;
rightPNum--;
}
}
//at no point should I have more rights then lefts
//so we'll go through string from left to right
// and fix it in a greedy way every time that happens
/*int biggestDifLocation=0;
for (int j=0; j<positionList.size();j++){
if(positionList.get(j).character=='(') leftPNum++;
else if (positionList.get(j).character==')') rightPNum++;
if(rightPNum-leftPNum>0) {
biggestDifLocation = findBiggestDifference(j);
if (biggestDifLocation<0){
illegal=true;
break;
}
positionList.get(biggestDifLocation).character = '(';
leftPNum++;
rightPNum--;
totalCost -= positionList.get(biggestDifLocation).difference;
}
}*/
if(rightPNum != leftPNum || illegal==true){
System.out.println(-1);//check if a solution couldn't be found
}
else {
System.out.println(totalCost);
System.out.println(inputArray);
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | f24008147f6310e97044dde66dd5aad2 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
public class Main{
public static class Position implements Comparable<Position>{
char character;
int difference;
boolean changeable;
int location;
Position(char newCharacter, int newDif, boolean newChangeable, int newLocation){
this.character = newCharacter;
this.difference = newDif; //how much we'll gain by changing from rp to lp
this.changeable = newChangeable; //whether we are allowed to alter this
this.location = newLocation;
}
@Override
public int compareTo(Position P){
return P.difference - this.difference;
}
}
public static String inputString = null;
public static int leftPNum = 0;
public static int rightPNum = 0;
public static Long totalCost = 0L;
public static PriorityQueue<Position> maxHeap = new PriorityQueue<Position>();
public static void main(String[] args){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String startString = null;
char[] inputArray;
String[] parsedString;
boolean illegal = false;
try {
inputString = in.readLine();
} catch (Exception e) {
}
inputArray = inputString.toCharArray();
for(int i=0; i<inputArray.length; i++){
if(inputArray[i]=='('){
leftPNum++;
}
else if(inputArray[i]==')'){
rightPNum++;
}
else{
try {
startString = in.readLine();
} catch (Exception e) {
}
parsedString = startString.split(" ");
//we are initially going to assume that the best circumstance in all right parens
maxHeap.offer(new Position(')',Integer.parseInt(parsedString[1])-Integer.parseInt(parsedString[0]), true, i));
inputArray[i]=')';
rightPNum++;
totalCost += Long.parseLong(parsedString[1]);
}
if(rightPNum - leftPNum > 0){
if(maxHeap.size()==0){ //if we need to replace something but there is nothing to replace, ie ())?
illegal = true;
break;
}
Position replacePos = maxHeap.poll();
inputArray[replacePos.location]='(';
totalCost -= replacePos.difference;
leftPNum++;
rightPNum--;
}
}
if(rightPNum != leftPNum || illegal==true){
System.out.println(-1);//check if a solution couldn't be found
}
else {
System.out.println(totalCost);
System.out.println(inputArray);
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | a46d875cb286f91ecf7a45857fc81b67 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
public class Main {
private static class Cost implements Comparable<Cost> {
int open;
int close;
int id;
int diff() {
return this.open - this.close;
}
Cost(int open, int close, int id) {
this.open = open;
this.close = close;
this.id = id;
}
@Override
public int compareTo(Cost o) {
return this.diff() - o.diff();
}
}
public static void main(String[] args) throws IOException {
String whichInputToUse = "System.in";
// String whichInputToUse = "input.txt";
BufferedReader in = new BufferedReader(new InputStreamReader("System.in".equals(whichInputToUse) ? System.in : new FileInputStream(whichInputToUse)));
String originalString = in.readLine();
char[] newString = originalString.toCharArray();
int stringLength = originalString.length();
// int[][] costOfEachParen = {};
PriorityQueue<Cost> allQuestions = new PriorityQueue<Cost>();
// int numberOfLeftParens = 0;
// int numberOfRightParens = 0;
int numberOfOpenParens = 0;
long totalCost = 0;
for (int i = 0; i < stringLength; i++) {
char nextCharacter = newString[i];
if ((nextCharacter == ')' && i == 0) || (nextCharacter == '(' && i == stringLength - 1)) {
System.out.println(-1);
return;
}
if (nextCharacter == '(') {
numberOfOpenParens++;
} else if (nextCharacter == ')') {
numberOfOpenParens--;
} else {
String[] nextNumbers = in.readLine().split("\\s+");
// costOfEachParen[i] = new int[]{Integer.parseInt(nextNumbers[0]), Integer.parseInt(nextNumbers[1])};
allQuestions.add(new Cost(Integer.parseInt(nextNumbers[0]), Integer.parseInt(nextNumbers[1]), i));
newString[i] = ')';
numberOfOpenParens--;
totalCost += Integer.parseInt(nextNumbers[1]);
}
if (numberOfOpenParens < 0) {
if (allQuestions.isEmpty()) {
System.out.println(-1);
return;
} else {
Cost biggestDifference = allQuestions.poll();
newString[biggestDifference.id] = '(';
totalCost += biggestDifference.diff();
numberOfOpenParens += 2;
}
}
}
if (numberOfOpenParens > 0) {
System.out.println(-1);
return;
}
System.out.println(totalCost);
System.out.println(newString);
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | d8adf7b321f3233cad2cc3345a960b02 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static class holder implements Comparable<holder>{
int qmIndex;
int firstCost;
int secondCost;
public holder(int qmIndex, int firstCost, int secondCost){
this.qmIndex = qmIndex;
this.firstCost = firstCost;
this.secondCost = secondCost;
}
public int compareTo(holder instance){
return ((this.firstCost - this.secondCost) - (instance.firstCost - instance.secondCost));
}
}
public static void main (String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = in.readLine();
char[] bracketArray = new char[line.length()];
if (line.length() % 2 == 1){ //if its odd, the braces will never match
System.out.println(-1);
System.exit(0);
}
for (int i = 0; i < line.length(); i++){
bracketArray[i] = line.charAt(i);
}
int secure = 0;
long cost = 0;
String[] FS;
PriorityQueue<holder> holderQueue = new PriorityQueue<holder>();
for (int i = 0; i < bracketArray.length; i++){
if (bracketArray[i] =='('){
secure++;
}
else if (bracketArray[i] == ')'){
secure--;
}
else if (bracketArray[i] == '?'){//determine
FS = in.readLine().split(" ");
int firstCost = Integer.parseInt(FS[0]);
int secondCost = Integer.parseInt(FS[1]);
secure--;
bracketArray[i] = ')';
holderQueue.add(new holder(i, firstCost, secondCost));
cost += secondCost;
}
if (secure < 0 ){ //rebalance
holder check = holderQueue.poll();
if (check == null){
System.out.println(-1);
System.exit(0);
}
bracketArray[check.qmIndex] = '(';
cost -= check.secondCost;
cost += check.firstCost;
secure += 2;
}
// System.out.println("Cost: "+cost);
}
//System.out.println(bracketArray[bracketArray.length-1]);
if (bracketArray[bracketArray.length-1] == '(' || bracketArray[0] == ')' || secure != 0){
System.out.println(-1);
System.exit(0);
}
System.out.println(cost);
for (int j = 0; j < bracketArray.length; j++){
System.out.print(bracketArray[j]);
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | dd17f3b67ba2c38ad8e0381a00c9eab6 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.io.*;
import java.util.*;
public class Temp2 {
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char[] arr = br.readLine().toCharArray();
long cost = 0;
int open=0;
PriorityQueue<Bracket> q = new PriorityQueue<Bracket>();
for (int i = 0; i < arr.length; i++)
{
switch (arr[i])
{
case '(':
open++;
break;
case ')':
open--;
break;
case '?':
open--;
arr[i] = ')';
StringTokenizer st = new StringTokenizer(br.readLine());
int o = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
q.add(new Bracket(i,o, c));
break;
default:
break;
}
if(open<0)
{
if(q.isEmpty())
{
System.out.println(-1);
return;
}
Bracket x = q.poll();
cost +=(long) x.open;
arr[x.ind] = '(';
open+=2;
}
}
if(open!=0)
{
System.out.println(-1);
return;
}
while(!q.isEmpty())
cost += (long)q.poll().close;
System.out.println(cost);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; i++)
sb.append(arr[i]);
System.out.println(sb);
}
static class Bracket implements Comparable<Bracket>
{
int open,close,ind;
public Bracket(int i,int o,int c)
{
ind = i;
close = c;
open = o;
}
public int compareTo(Bracket o)
{
return -(close-open)+(o.close-o.open);
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | 84e1098a0eec9be360367f6cef1c4a9a | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
String s = in.next();
char[] st = s.toCharArray();
int count = 0;
int temp, tem;
int mark = 0;
long ans = 0;
PriorityQueue<Node> q = new PriorityQueue<Node>();
for (int i = 0; i < st.length; i++) {
if (st[i] == '(') count++;
if (st[i] == ')' || st[i] == '?') count--;
if (st[i] == '?') {
temp = in.nextInt();
tem = in.nextInt();
st[i] = ')';
q.add(new Node(i, (tem - temp)));
ans = ans + tem;
}
if (count < 0 && q.isEmpty()) {
mark = 1;
break;
}
if (count < 0) {
Node n = q.poll();
st[n.index] = '(';
count = count + 2;
ans = ans - n.val;
}
}
if (count > 0) {
mark = 1;
}
if (mark == 1) System.out.println("-1");
else {
System.out.println(ans);
for (int i = 0; i < st.length; i++) System.out.print(st[i]);
}
}
public static void print(char[] st) {
for (int i = 0; i < st.length; i++) System.out.print(st[i]);
}
static class Node implements Comparable<Node> {
int index;
int val;
Node(int indx, int vl) {
index = indx;
val = vl;
}
public int compareTo(Node x) {
if (x.val == val) return 0;
if (x.val < val) return -1;
return 1;
}
public String toString() {
return "[" + index + "," + val + "]";
}
}
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 | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | d4a48efd3bf45ce291aff1da0545d4e8 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Prob3D {
static class Decision implements Comparable<Decision>
{
int index;
int openCost;
int closedCost;
public Decision(int i, int o, int c)
{
this.index = i;
this.openCost = o;
this.closedCost = c;
}
public int getOpenSavings() //How much benefit is there to choosing '(' instead of ')'
{
return this.closedCost - this.openCost;
}
public int getIndex()
{
return this.index;
}
public int getOpenCost() {
return openCost;
}
public int getClosedCost() {
return closedCost;
}
@Override
public int compareTo(Decision arg0) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if(this.getOpenSavings() > arg0.getOpenSavings())
return BEFORE;
if(this.getOpenSavings() < arg0.getOpenSavings())
return AFTER;
return EQUAL;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char[] sequence = br.readLine().toCharArray();
StringTokenizer tokenizer = new StringTokenizer("");
int openCount = 0; //Number of '(' have we encountered
int span = 0; //Number of '?'s that have been put into pq
int openCost = 0;
int closedCost = 0;
long totalCost = 0;
Decision nextDecision = null;
PriorityQueue<Decision> pq = new PriorityQueue<Decision>();
for(int i=0; i<sequence.length; i++)
{
if(sequence[i]=='(')
openCount++;
else if(sequence[i] == ')')
openCount--;
else
{
span++;
tokenizer = new StringTokenizer(br.readLine());
openCost = Integer.parseInt(tokenizer.nextToken());
closedCost = Integer.parseInt(tokenizer.nextToken());
pq.add(new Decision(i, openCost, closedCost));
}
if(i==sequence.length-1 && (openCount!=span)) //If at end we have more open than we can close, no solution
{
totalCost = -1;
break;
}
if(openCount<0 && span<=0) //If more closed than can be opened, no solution
{
totalCost = -1;
break;
}
while(openCount-span < 0 && totalCost>-1) //Can't all be ')' so assign '(' to most economical slots
{
nextDecision = pq.poll();
sequence[nextDecision.getIndex()] = '(';
totalCost += nextDecision.getOpenCost();
openCount++;
span--;
}
}
if(totalCost < 0) //No solution found
System.out.println(-1);
else
{
while(!pq.isEmpty()) //Remaining slots get ')'
{
nextDecision = pq.poll();
sequence[nextDecision.getIndex()] = ')';
totalCost += nextDecision.getClosedCost();
}
System.out.println(totalCost);
System.out.println(sequence);
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | 1300ca8fc96dd12a0860155e1044406e | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class CodeForces {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
char[] s = br.readLine().toCharArray();
Queue<ClosedBracket> closedBrackets = new PriorityQueue<>(Comparator.comparingInt(f -> f.priceToChangeToOpen));
int open = 0;
long totalCost = 0;
for (int i = 0; i < s.length; i++) {
char c = s[i];
if (c == '(') {
open++;
} else if (c == ')') {
open--;
} else {
String[] p = br.readLine().split(" ");
int toOpen = Integer.parseInt(p[0]);
int toClose = Integer.parseInt(p[1]);
closedBrackets.add(new ClosedBracket(i, toOpen - toClose));
s[i] = ')';
open--;
totalCost += toClose;
}
if (open < 0) {
if (closedBrackets.isEmpty()) {
System.out.println(-1);
return;
}
ClosedBracket closedBracket = closedBrackets.poll();
totalCost += closedBracket.priceToChangeToOpen;
s[closedBracket.index] = '(';
open += 2;
}
}
if (open > 0) {
System.out.println(-1);
} else {
System.out.println(totalCost);
System.out.println(new String(s));
}
}
static class ClosedBracket {
int index;
int priceToChangeToOpen;
public ClosedBracket(int index, int priceToChangeToOpen) {
this.index = index;
this.priceToChangeToOpen = priceToChangeToOpen;
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | 7ffd625833407b618e8fc1e68e12457c | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class CodeForces {
public static void main(String[] args) {
FastReader reader = new FastReader();
char[] s = reader.nextLine().toCharArray();
Queue<ClosedBracket> closedBrackets = new PriorityQueue<>(Comparator.comparingInt(f -> f.priceToChangeToOpen));
int open = 0;
long totalCost = 0;
for (int i = 0; i < s.length; i++) {
char c = s[i];
if (c == '(') {
open++;
} else if (c == ')') {
open--;
} else {
int toOpen = reader.nextInt();
int toClose = reader.nextInt();
closedBrackets.add(new ClosedBracket(i, toOpen - toClose));
s[i] = ')';
open--;
totalCost += toClose;
}
if (open < 0) {
if (closedBrackets.isEmpty()) {
System.out.println(-1);
return;
}
ClosedBracket closedBracket = closedBrackets.poll();
totalCost += closedBracket.priceToChangeToOpen;
s[closedBracket.index] = '(';
open += 2;
}
}
if (open > 0) {
System.out.println(-1);
} else {
System.out.println(totalCost);
System.out.println(new String(s));
}
}
static class ClosedBracket {
int index;
int priceToChangeToOpen;
public ClosedBracket(int index, int priceToChangeToOpen) {
this.index = index;
this.priceToChangeToOpen = priceToChangeToOpen;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | de39e6be2e62b2f6905044332701d971 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.util.PriorityQueue;
import java.util.Scanner;
public class P3D {
static class Node {
int idx;
int cost;
Node(int idx, int cost) {
this.idx = idx;
this.cost = cost;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[] ch = sc.nextLine().toCharArray();
int status = 0;
long totalCost = 0;
PriorityQueue<Node> queue = new PriorityQueue<>((n1, n2) -> Integer.valueOf(n1.cost).compareTo(n2.cost));
for (int i = 0; i < ch.length; ++i) {
switch (ch[i]) {
case '(':
++status;
break;
case ')':
--status;
break;
case '?':
ch[i] = ')';
--status;
int l = sc.nextInt();
int r = sc.nextInt();
totalCost += r;
queue.add(new Node(i, l - r));
break;
}
if (status == -1 && !queue.isEmpty()) {
Node n = queue.poll();
totalCost += n.cost;
ch[n.idx] = '(';
status += 2;
}
if (status < 0) {
System.out.println(-1);
return;
}
}
if (status != 0) {
System.out.println(-1);
} else {
System.out.println(totalCost);
System.out.println(new String(ch));
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | 41dca848d84e15c9264fb54608d10ea6 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.io.*;
import java.util.*;
public class Least_Cost_Bracket_Sequence {
static class brac implements Comparable<brac>{
int num,lc,rc;
int diff=lc-rc;
char choice = ')';
brac () {
}
@Override
public int compareTo(brac b) {
return this.diff - b.diff;
}
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
char[] c = br.readLine().toCharArray();
int n=0;
for (int i = 0; i < c.length; i++)
if (c[i] == '?')
n++;
brac [] q= new brac[n];
//TreeMap<Integer,brac> L = new TreeMap<Integer,brac>();
for (int j = 0; j < n; j++) {
String[] ss = br.readLine().split(" ");
q[j]=new brac();
q[j].lc = Integer.parseInt(ss[0]);
q[j].rc = Integer.parseInt(ss[1]);
q[j].diff=q[j].lc-q[j].rc;
}
for (int i = 0,j=0; i < c.length; i++)
{
if (c[i] == '?')
{
q[j].num=i;
j++;
}
}
PriorityQueue<brac> qq = new PriorityQueue<>();
int net=0;
for(int i=0,j=0;i<c.length;i++)
{
if(c[i]=='(')
net++;
else
if(c[i]==')')
net--;
else
{
qq.add(q[j]);
net--;
j++;
}
if(net<0)
{
brac p = qq.poll();
if (p == null) {
System.out.println(-1);
return;
}
// if(L.isEmpty())
// {pw.println(-1);return;}
// L.get(L.firstKey()).choice='(';
// L.remove(L.firstKey());
p.choice='(';
net+=2;
}
}
long opti=0;
if(net!=0)
{
System.out.println(-1);
return;
}
for(int i=0;i<n;i++)
{
opti=opti+(q[i].choice=='(' ? q[i].lc:q[i].rc);
c[q[i].num]=q[i].choice;
}
pw.println(opti);
pw.println(new String(c));
pw.close();
}
} | Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | be02f41e5be7c214f01b79664c862864 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | /* 合 */
import java.io.*;
import java.util.*;
import java.math.*;
public final class lcbs
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static FastScanner sc=new FastScanner(br);
static PrintWriter out=new PrintWriter(System.out);
static Random rnd=new Random();
static List<Integer> al=new ArrayList<Integer>();
public static void main(String args[]) throws Exception
{
char[] a=sc.next().toCharArray();
for(int i=0;i<a.length;i++)
{
if(a[i]=='?')
{
al.add(i);
}
}
int n=al.size();Pair[] arr=new Pair[n];
for(int i=0;i<n;i++)
{
arr[i]=new Pair(al.get(i),sc.nextInt(),sc.nextInt());
}
char[] res=new char[a.length];int x=0,y=0,z=0,ptr=0;
for(int i=0;i<a.length;i++)
{
if(a[i] != '?')
{
res[i]=a[i];
}
else
{
res[i]='x';
}
}
TreeSet<Pair> ts=new TreeSet<>();boolean ans=true;long now=0,sum=0;
for(int i=0;i<a.length;i++)
{
if(a[i] == '(') x++;
if(a[i] == ')') y++;
if(a[i] == '?')
{
ts.add(new Pair(i,arr[ptr].l-arr[ptr].r,ptr));ptr++;z++;
}
if( y + z > x )
{
if(ts.size() == 0)
{
ans=false;break;
}
Pair curr = ts.first(); res[curr.idx]='(';
ts.remove(curr);long add = arr[curr.r].l;now+=add;
x++;z--;
}
}
if(ans)
{
x=0;y=0;
while(ts.size()>0)
{
Pair curr=ts.first();res[curr.idx]=')';
now+=arr[curr.r].r; ts.remove(curr);
}
for(int i=0;i<a.length;i++)
{
if(res[i]=='(')
{
x++;
}
else
{
y++;
}
}
if(x == y)
{
out.println(now+"\n"+new String(res));
}
else
{
out.println(-1);
}
}
else
{
out.println(-1);
}
out.close();
}
}
class Pair implements Comparable<Pair>
{
int idx,l,r;
public Pair(int idx,int l,int r)
{
this.idx=idx;this.l=l;this.r=r;
}
public int compareTo(Pair x)
{
if(this.l==x.l)
{
return Integer.compare(this.idx,x.idx);
}
return Integer.compare(this.l,x.l);
}
}
class FastScanner
{
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public String next() throws Exception {
return nextToken().toString();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
} | Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | d55802b1f7b051cf022ed391557cf9cf | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.PriorityQueue;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.AbstractCollection;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
StringBuilder s = new StringBuilder(in.n());
int len = s.length();
int open = 0;
long c = 0;
PriorityQueue<Pair> pq = new PriorityQueue<>(10, (a, b) -> a.first == b.first ? b.second - a.second : b.first - a.first);
int a, b;
for (int i = 0; i < len; ++i) {
open = open + (s.charAt(i) == '(' ? 1 : 0) - (s.charAt(i) != '(' ? 1 : 0);
if (s.charAt(i) == '?') {
a = in.ni();
b = in.ni();
s.setCharAt(i, ')');
pq.add(new Pair(-(a - b), i));
c += b;
}
if (open < 0) {
if (pq.isEmpty()) break;
Pair temp = pq.poll();
s.setCharAt(temp.second, '(');
c += -temp.first;
open += 2;
}
}
if (open != 0)
out.println(-1);
else
out.println(c + "\n" + s.toString());
}
class Pair {
int first;
int second;
Pair(int a, int b) {
first = a;
second = b;
}
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
public String n() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(n());
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | c337eecd55734b1713ddbfd4e0dee399 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.lang.Math.*;
// Solution is at the bottom of code
public class D implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
OutputWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new D(), "", 128 * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
solve();
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
String delim = " ";
String readString() throws IOException{
while(!tok.hasMoreTokens()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
return tok.nextToken(delim);
}
String readLine() throws IOException{
return in.readLine();
}
/////////////////////////////////////////////////////////////////
final char NOT_A_SYMBOL = '\0';
char readChar() throws IOException{
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
}
char[] readCharArray() throws IOException{
return readLine().toCharArray();
}
/////////////////////////////////////////////////////////////////
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) {
array[index] = readInt();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
int[] readIntArrayWithDecrease(int size) throws IOException {
int[] array = readIntArray(size);
for (int i = 0; i < size; ++i) {
array[i]--;
}
return array;
}
///////////////////////////////////////////////////////////////////
int[][] readIntMatrix(int rowsCount, int columnsCount) throws IOException {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArray(columnsCount);
}
return matrix;
}
int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) throws IOException {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
}
return matrix;
}
///////////////////////////////////////////////////////////////////
long readLong() throws IOException{
return Long.parseLong(readString());
}
long[] readLongArray(int size) throws IOException{
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
double[] readDoubleArray(int size) throws IOException{
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
BigInteger readBigInteger() throws IOException {
return new BigInteger(readString());
}
BigDecimal readBigDecimal() throws IOException {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
Point readPoint() throws IOException{
int x = readInt();
int y = readInt();
return new Point(x, y);
}
Point[] readPointArray(int size) throws IOException{
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
throws IOException{
@SuppressWarnings("unchecked")
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<Integer>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
/////////////////////////////////////////////////////////////////////
static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return value1 - value2;
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static Comparator<IntIndexPair> decreaseComparator = new Comparator<IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return -(value1 - value2);
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
int value, index;
public IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
public int getRealIndex() {
return index + 1;
}
}
IntIndexPair[] readIntIndexArray(int size) throws IOException {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
static class OutputWriter extends PrintWriter {
final int DEFAULT_PRECISION = 12;
protected int precision;
protected String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
private String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
public void printWithSpace(double d){
printf(formatWithSpace, d);
}
public void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
public void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
static final int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
static final boolean check(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
static final boolean checkBit(int mask, int bit){
return (mask & (1 << bit)) != 0;
}
/////////////////////////////////////////////////////////////////////
static final long getSum(int[] array) {
long sum = 0;
for (int value: array) {
sum += value;
}
return sum;
}
static final Point getMinMax(int[] array) {
int min = array[0];
int max = array[0];
for (int index = 0, size = array.length; index < size; ++index, ++index) {
int value = array[index];
if (index == size - 1) {
min = min(min, value);
max = max(max, value);
} else {
int otherValue = array[index + 1];
if (value <= otherValue) {
min = min(min, value);
max = max(max, otherValue);
} else {
min = min(min, otherValue);
max = max(max, value);
}
}
}
return new Point(min, max);
}
/////////////////////////////////////////////////////////////////////
final static char
OPENED_SIGN = '(',
NONE_SIGN = '?',
CLOSED_SIGN = ')';
final static String STATE_SIGNS = "" + OPENED_SIGN + NONE_SIGN + CLOSED_SIGN;
final static int
OPENED = STATE_SIGNS.indexOf(OPENED_SIGN),
NONE = STATE_SIGNS.indexOf(NONE_SIGN),
CLOSED = STATE_SIGNS.indexOf(CLOSED_SIGN);
final static int[] STATES = { OPENED, NONE, CLOSED };
final static int STATES_COUNT = STATES.length;
final static int[] BALANCE_DELTAS = { 1, 0, -1 };
final static long INF = 1000L * 1000 * 1000 * 1000;
static class ValueIndexPair extends AbstractMap.SimpleEntry<Long, Integer> {
/**
*
*/
private static final long serialVersionUID = -4326518412082051685L;
public ValueIndexPair(Long key, Integer value) {
super(key, value);
}
}
static class MultiIndexedTreeSet extends TreeMap<Long, TreeSet<Integer>> {
final static ValueIndexPair EMPTY = new ValueIndexPair(INF, -1);
/**
*
*/
private static final long serialVersionUID = 7671098813940210758L;
protected int size;
public MultiIndexedTreeSet() {
super();
size = 0;
}
@Override
public int size() {
return size;
}
public void add(long value, int index) {
TreeSet<Integer> indexes = get(value);
if (indexes == null) {
put(value, indexes = new TreeSet<Integer>());
}
indexes.add(index);
++size;
}
public void remove(long value, int index) {
TreeSet<Integer> indexes = get(value);
indexes.remove(index);
if (indexes.size() == 0) {
remove(value);
};
--size;
}
public ValueIndexPair pollFirst() {
if (size() == 0) {
return EMPTY;
}
Map.Entry<Long, TreeSet<Integer>> firstEntry = firstEntry();
long firstValue = firstEntry.getKey();
int firstIndex = firstEntry.getValue().first();
remove(firstValue, firstIndex);
return new ValueIndexPair(firstValue, firstIndex);
}
}
void solve() throws IOException {
char[] sequence = readCharArray();
int n = sequence.length;
int[] states = new int[n];
for (int i = 0; i < n; ++i) {
states[i] = STATE_SIGNS.indexOf(sequence[i]);
}
int nonesCount = 0;
for (int state : states) {
nonesCount += (state == NONE ? 1 : 0);
}
Point[] noneCosts = readPointArray(nonesCount);
long[][] costs = new long[STATES_COUNT][n];
for (int i = 0, noneIndex = 0; i < n; ++i) {
costs[1][i] = INF;
if (states[i] == 1) {
costs[OPENED][i] = noneCosts[noneIndex].x;
costs[CLOSED][i] = noneCosts[noneIndex].y;
++noneIndex;
} else {
costs[states[i]][i] = 0;
costs[STATES_COUNT - 1 - states[i]][i] = INF;
}
}
long[] changeCosts = new long[n];
for (int i = 0; i < n; ++i) {
int minState = NONE;
for (int state : STATES) {
if (costs[minState][i] > costs[state][i]) {
minState = state;
}
}
states[i] = minState;
changeCosts[i] = abs(costs[OPENED][i] - costs[CLOSED][i]);
}
if (!equalization(n, states, changeCosts)) {
out.println(-1);
return;
}
int balance = balancing(n, states, changeCosts);
if (balance > 0) {
mirroring(balance, states, changeCosts);
balance = balancing(n, states, changeCosts);
mirroring(balance, states, changeCosts);
}
if (balance < 0) {
out.println(-1);
return;
}
long totalCost = 0;
for (int i = 0; i < n; ++i) {
totalCost += costs[states[i]][i];
}
if (totalCost >= INF) {
out.println(-1);
} else {
out.println(totalCost);
for (int i = 0; i < n; ++i) {
out.print(STATE_SIGNS.charAt(states[i]));
}
out.println();
}
}
void mirroring(int n, int[] states, long[] changeCosts) {
int[] newStates = new int[n];
long[] newChangeCosts = new long[n];
for (int i = 0, j = n - 1; i < n; ++i, --j) {
newStates[j] = STATES_COUNT - 1 - states[i];
newChangeCosts[j] = changeCosts[i];
}
for (int i = 0; i < n; ++i) {
states[i] = newStates[i];
changeCosts[i] = newChangeCosts[i];
}
}
int balancing(int n, int[] states, long[] changeCosts) {
MultiIndexedTreeSet suffixOpened = new MultiIndexedTreeSet();
MultiIndexedTreeSet prefixClosed = new MultiIndexedTreeSet();
for (int i = n - 1; i >= 0; --i) {
if (states[i] == OPENED) {
suffixOpened.add(changeCosts[i], i);
}
}
int balance = 0;
for (int i = 0; i < n; ++i) {
balance += BALANCE_DELTAS[states[i]];
if (states[i] == CLOSED) {
prefixClosed.add(changeCosts[i], i);
}
if (states[i] == OPENED) {
suffixOpened.remove(changeCosts[i], i);
}
while (balance < 0) {
if (!balancing(prefixClosed, OPENED, states, changeCosts)
||
!balancing(suffixOpened, CLOSED, states, changeCosts)) {
return -1;
}
balance += BALANCE_DELTAS[OPENED] - BALANCE_DELTAS[CLOSED];
}
}
return balance;
}
boolean balancing(MultiIndexedTreeSet oldStates, int newState,
int[] states, long[] changeCosts) {
ValueIndexPair first = oldStates.pollFirst();
if (first.getKey().equals(INF)) {
return false;
}
int index = first.getValue();
states[index] = newState;
changeCosts[index] = -changeCosts[index];
return true;
}
boolean equalization(int n, int[] states, long[] changeCosts) {
MultiIndexedTreeSet opened = new MultiIndexedTreeSet();
MultiIndexedTreeSet closed = new MultiIndexedTreeSet();
for (int i = 0; i < n; ++i) {
if (states[i] == OPENED) {
opened.add(changeCosts[i], i);
} else {
closed.add(changeCosts[i], i);
}
}
if (!equalization(opened, closed, states, changeCosts, OPENED)
||
!equalization(closed, opened, states, changeCosts, CLOSED)) {
return false;
}
return true;
}
boolean equalization(MultiIndexedTreeSet small, MultiIndexedTreeSet large,
int[] states, long[] changeCosts, int smallState) {
while (small.size() < large.size()) {
ValueIndexPair firstLarge = large.pollFirst();
int index = firstLarge.getValue();
if (changeCosts[index] == INF) {
return false;
}
changeCosts[index] = -changeCosts[index];
states[index] = smallState;
small.add(changeCosts[index], index);
}
return true;
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | e73a7060fa2de12a35f473af136e8dad | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.io.BufferedReader;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static BufferedReader reader;
public static String readString(){
try {
return reader.readLine().trim();
} catch (IOException exception){
throw new IOError(exception);
}
}
public static int readInt(){
return Integer.parseInt(readString());
}
public static int[] readInts(){
String[] parts = readString().split(" ");
int[] integers = new int[parts.length];
for (int i = 0; i<integers.length; i++){
integers[i] = Integer.parseInt(parts[i]);
}
return integers;
}
public static double readDouble(){
return Double.parseDouble(readString());
}
public static double[] readDoubles(){
String[] parts = readString().split(" ");
double[] integers = new double[parts.length];
for (int i = 0; i<integers.length; i++){
integers[i] = Double.parseDouble(parts[i]);
}
return integers;
}
static class Question implements Comparable<Question> {
final int cost1, cost2, diffCost, position;
Question (int cost1, int cost2, int position) {
this.cost1 = cost1;
this.cost2 = cost2;
this.diffCost = cost1-cost2;
this.position = position;
}
@Override
public int compareTo(Question o) {
return this.diffCost - o.diffCost;
}
}
public static void main(String[] args) {
reader = new BufferedReader(new InputStreamReader(System.in));
String line = readString();
StringBuilder builder = new StringBuilder(line);
ArrayList<Question> costs = new ArrayList<Question>();
long totalCost = 0l;
for (int i = 0; i < line.length(); i++){
if (line.charAt(i)=='?') {
int[] c = readInts();
costs.add(new Question(c[0], c[1], i));
}
}
int openParenthesis = 0;
int maxClosingParenthesis = 0;
int closingParensPosition = 0;
ListIterator<Question> nextCost = costs.listIterator();
for (int i = 0; i < line.length(); i++) {
switch (line.charAt(i)) {
case '(':
openParenthesis++;
break;
case ')':
openParenthesis--;
if (openParenthesis < maxClosingParenthesis) {
maxClosingParenthesis = openParenthesis;
closingParensPosition = i+1;
}
break;
default:
if (nextCost.next().diffCost <= 0) {
openParenthesis++;
} else {
openParenthesis--;
if (openParenthesis < maxClosingParenthesis) {
maxClosingParenthesis = openParenthesis;
closingParensPosition = i+1;
}
}
break;
}
}
PriorityQueue<Question> queue = new PriorityQueue<Question>();
openParenthesis = 0;
nextCost = costs.listIterator();
for (int i = 0; i < closingParensPosition; i++) {
switch (line.charAt(i)){
case '(':
openParenthesis++;
break;
case ')':
openParenthesis--;
break;
default:
Question next = nextCost.next();
if (next.diffCost <= 0){
openParenthesis++;
builder.replace(i,i+1,"(");
totalCost += next.cost1;
} else {
openParenthesis--;
builder.replace(i,i+1,")");
totalCost += next.cost2;
queue.add(next);
}
}
if (openParenthesis == -1) {
if (queue.isEmpty()) {
System.out.println(-1);
return;
}
openParenthesis = 1;
Question question = queue.poll();
builder.replace(question.position, question.position+1, "(");
totalCost += question.diffCost;
}
}
queue = new PriorityQueue<Question>(2, Collections.reverseOrder());
openParenthesis = 0;
Collections.reverse(costs);
nextCost = costs.listIterator();
for (int i = line.length()-1; i >= closingParensPosition; i--) {
switch (line.charAt(i)){
case ')':
openParenthesis++;
break;
case '(':
openParenthesis--;
break;
default:
Question next = nextCost.next();
if (next.diffCost > 0){
openParenthesis++;
builder.replace(i,i+1,")");
totalCost += next.cost2;
} else {
openParenthesis--;
builder.replace(i,i+1,"(");
totalCost+= next.cost1;
queue.add(next);
}
}
if (openParenthesis == -1) {
if (queue.isEmpty()){
System.out.println(-1);
return;
}
Question question = queue.poll();
openParenthesis = 1;
builder.replace(question.position,question.position+1, ")");
totalCost -= question.diffCost;
}
}
System.out.println(totalCost);
System.out.println(builder.toString());
}
} | Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | b9ac7b02d9df66a2fea7f7a219e15518 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.util.PriorityQueue;
import java.util.Scanner;
public class LeastCostBracketSequence_3D {
private static class Bracket implements Comparable<Bracket> {
int costDiff;
int index;
Bracket(int costDiff, int index) {
this.costDiff = costDiff;
this.index = index;
}
public int compareTo(Bracket other) {
if (this.costDiff > other.costDiff)
return -1;
else if (this.costDiff == other.costDiff)
return 0;
else
return 1;
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
PriorityQueue<Bracket> pq = new PriorityQueue<>();
int diff = 0, oc = 0, cc = 0; // oc-opening cost, cc
// -closing,
// inicijalizirao sam ih
// zbog might not...
// errora
long leastCost = 0;
char[] brackets = s.next().toCharArray();
Bracket b;
for (int i = 0, n = brackets.length; i < n; i++) {
if (brackets[i] == '(') {
diff++;
} else if (brackets[i] == ')') {
diff--;
} else {
brackets[i] = ')';
diff--;
oc = s.nextInt();
cc = s.nextInt();
leastCost += cc;
pq.add(new Bracket(cc - oc, i));
}
if (diff < 0) {
if (pq.isEmpty())
break;
b = pq.poll();
diff += 2;
leastCost -= (b.costDiff);
brackets[b.index] = '(';
}
}
if (diff != 0) {
System.out.println(-1);
} else {
System.out.println(leastCost);
for (char c : brackets) {
System.out.print(c);
}
}
}
} | Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | 662eb8a556ac3253fcae385f730f5a23 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | 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.PriorityQueue;
import java.util.StringTokenizer;
public class LeastCostBracketSequence {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
char[] s = sc.nextLine().toCharArray();
int n = s.length;
Element a[] = new Element[n];
for (int i = 0; i < n; i++)
if (s[i] == '?')
a[i] = new Element(sc.nextInt(), sc.nextInt(), i);
PriorityQueue<Element> pq = new PriorityQueue<>();
int size = 0;
long sum = 0;
int c = 0;
for (int i = 0; i < n; i++) {
if (c < 0)
break;
if (s[i] == '(')
c++;
else if (s[i] == ')') {
c--;
}
else {
s[i] = ')';
sum += a[i].b;
pq.add(a[i]);
size++;
c--;
}
if (c < 0) {
if (size == 0)
break;
Element e = pq.remove();
size--;
sum += e.a - e.b;
s[e.idx] = '(';
c+=2;
}
}
if (c == 0) {
out.println(sum);
out.println(new String(s));
}
else
out.println(-1);
out.flush();
out.close();
}
static class Element implements Comparable<Element> {
int a, b, idx;
public Element(int x, int y, int i) {
a = x;
b = y;
idx = i;
}
@Override
public int compareTo(Element o) {
int d1 = a-b;
int d2 = o.a-o.b;
return Integer.compare(d1, d2);
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner(FileReader f) {
br = new BufferedReader(f);
}
public Scanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean Ready() throws IOException {
return br.ready();
}
public void waitForInput(long time) {
long ct = System.currentTimeMillis();
while(System.currentTimeMillis() - ct < time) {};
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | 9feb588cad7d357482444984a52e9c46 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
public class Main {
public static class Paren implements Comparable<Paren> {
int cost;
int index;
public Paren(int c, int i) {
cost = c;
index = i;
}
@Override
public int compareTo(Paren p) {
return cost > p.cost ? 1 : -1;
}
}
public static void main(String[] args) {
try{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
char[] bs = b.readLine().toCharArray();
int n=0;
long sum=0;
PriorityQueue<Paren> queue = new PriorityQueue<Paren>();
for(int i=0; i<bs.length; i++){
if(bs[i] == '('){
n++;
}
if(bs[i] == ')'){
n--;
}
if(bs[i]=='?'){
bs[i] = ')';
n--;
String[] inputs = b.readLine().split(" ");
int x = Integer.parseInt(inputs[0]);
int y = Integer.parseInt(inputs[1]);
sum += y;
queue.add(new Paren((x - y), i));
}
if (n < 0) {
if(queue.isEmpty()){
System.out.println("-1");
return;
}
n += 2;
Paren paren = queue.poll();
sum += paren.cost;
bs[paren.index] = '(';
}
}
if (n != 0) {
System.out.println("-1");
} else {
System.out.println(sum);
System.out.println(bs);
}
}
catch(IOException io){
// io.printStackTrace();
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | b7b77c1ff17eb0d9b8b46c85455ef7f0 | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class LeastCostBracketSequence {
static class Bracket implements Comparable<Bracket> {
int idx, cost;
Bracket(int i, int c) {
idx = i;
cost = c;
}
@Override
public String toString() {
return idx + " " + cost;
}
@Override
public int compareTo(Bracket b) {
return cost - b.cost;
}
}
public static void main(String[] args) throws IOException {
MyScanner sc = new MyScanner(System.in);
char[] c = sc.next().toCharArray();
int n = c.length;
long ans = 0, bracket = 0;
PriorityQueue<Bracket> pq = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
if (c[i] == '(')
bracket++;
else if (c[i] == ')')
bracket--;
else if (c[i] == '?') {
int open = sc.nextInt(), close = sc.nextInt();
pq.add(new Bracket(i, open - close));
ans += close;
c[i] = ')';
bracket--;
}
if (bracket < 0) {
if (pq.isEmpty()) {
ans = -1;
break;
}
Bracket b = pq.poll();
c[b.idx] = '(';
ans += b.cost;
bracket += 2;
}
}
if(bracket != 0)
ans = -1;
System.out.println(ans);
if(ans != -1)
System.out.println(new String(c));
}
static class MyScanner {
StringTokenizer st;
BufferedReader br;
public MyScanner(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 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 String nextLine() throws IOException {
return br.readLine();
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | 5ea75b164701b6b12e487ea0eb375c2a | train_000.jsonl | 1267963200 | This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest. | 64 megabytes | //package com.company;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class LeastCostBracketSequence {
public static void main(String[] args) {
FastScanner scanner = new FastScanner();
String brackets = scanner.next();
StringBuilder builder = new StringBuilder(brackets);
PriorityQueue<int[]> queue = new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
return b[2]-b[1]-a[2]+a[1];
}
});
int length = builder.length();
int unmatched = 0;
long cost = 0;
int openingCost,closingCost;
for (int i = 0; i < length; i++) {
if (builder.charAt(i) == '(') {
unmatched++;
} else if (builder.charAt(i) == ')') {
unmatched--;
} else if (builder.charAt(i) == '?') {
openingCost = scanner.nextInt();
closingCost = scanner.nextInt();
cost += closingCost;
builder.replace(i, i + 1, ")");
queue.add(new int[]{i, openingCost, closingCost});
unmatched--;
}
if (unmatched < 0) {
if (queue.size() == 0) {
break;
}
int[] b = queue.poll();
unmatched += 2;
builder.replace(b[0], b[0] + 1, "(");
cost = cost + b[1] - b[2];
}
}
if (unmatched != 0) {
System.out.println(-1);
return;
}
System.out.println(cost);
System.out.println(builder.toString());
}
public static class FastScanner {
private StringTokenizer st;
private BufferedReader br;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["(??)\n1 2\n2 8"] | 1 second | ["4\n()()"] | null | Java 8 | standard input | [
"greedy"
] | 970cd8ce0cf7214b7f2be337990557c9 | The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai, bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one. | 2,600 | Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them. | standard output | |
PASSED | 2a514aa3fc77f92918dbc64e293f7183 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.util.*;
public class Task {
public static void main(String[] args) throws IOException {
new Task().solve();
}
PrintWriter out;
int cnt = 0;
int n;
boolean[] used;
int[] use;
LinkedList<Integer>[] gr;
ArrayList<Integer> tsort = new ArrayList<Integer>();
int[] comp;
int[] compsize;
int[] mt;
int[] a;
int k;
boolean[][] g;
long dp[];
int m;
int[] list;
int d;
int ver = 0;
int mod = 1000000007;
void solve() throws IOException{
Reader in = new Reader("output.txt");
out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) );
//out = new PrintWriter(new FileWriter(new File("output.txt")));
d = in.nextInt();
n = in.nextInt();
g = new boolean[n][n];
list = new int[n];
for (int i = 0; i < n; i++)
list[i] = in.nextInt();
gr = new LinkedList[n];
for (int i = 0; i < n; i++)
gr[i] = new LinkedList<Integer>();
for (int i = 0; i < n-1; i++)
{
int x = in.nextInt()-1;
int y = in.nextInt()-1;
g[x][y] = true;
g[y][x] = true;
gr[x].add(y);
gr[y].add(x);
}
dp = new long[n];
use = new int[n];
long cnt = 0;
for (int i = 0; i < n; i++) {
ver = i;
Arrays.fill(dp, 0);
dfs(i, -1);
cnt = (cnt+dp[i])%mod;
//System.out.println();
}
out.print(cnt);
out.flush();
out.close();
}
void dfs(int v, int p) {
//System.out.println(v+1);
use[v] = 1;
dp[v] = 1;
for (int i : gr[v])
if (i != p) {
if (list[i] < list[ver] || list[i] > list[ver]+d) continue;
if (list[i] == list[ver] && i < ver) continue;
dfs(i, v);
dp[v] = (dp[v]*(dp[i]+1))%mod;
}
}
long pow(int x, int m) {
if (m == 0)
return 1;
return x*pow(x, m-1);
}
}
class Pair implements Comparable<Pair> {
int v;
int i;
Pair (int v, int i) {
this.v = v;
this.i = i;
}
@Override
public int compareTo(Pair p) {
if (v > p.v)
return 1;
if (v < p.v)
return -1;
return 0;
}
}
class Item implements Comparable<Item> {
int v;
int l;
int z;
Item(int v, int l, int z) {
this.v = v;
this.l = l;
this.z = z;
}
@Override
public int compareTo(Item item) {
if (l > item.l)
return 1;
else
if (l < item.l)
return -1;
else {
if (z > item.z)
return 1;
else
if (z < item.z)
return -1;
return 0;
}
}
}
class Reader {
StringTokenizer token;
BufferedReader in;
public Reader(String file) throws IOException {
//in = new BufferedReader( new FileReader( file ) );
in = new BufferedReader( new InputStreamReader( System.in ) );
}
public byte nextByte() throws IOException {
return Byte.parseByte(Next());
}
public int nextInt() throws IOException {
return Integer.parseInt(Next());
}
public long nextLong() throws IOException {
return Long.parseLong(Next());
}
public String nextString() throws IOException {
return in.readLine();
}
public String Next() throws IOException {
while (token == null || !token.hasMoreTokens()) {
token = new StringTokenizer(in.readLine());
}
return token.nextToken();
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | 591e3a7aa23e7adfaad717f4e2867074 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class tmp {
Scanner sc = new Scanner(System.in);
final int MOD = 1000000007;
ArrayList<Integer>[] tree;
boolean[] v;
int[] a;
int n, d;
void run() {
d = sc.nextInt();
n = sc.nextInt();
a = new int[n];
tree = new ArrayList[n];
for (int i = 0; i < n; i++) {
tree[i] = new ArrayList<Integer>();
a[i] = sc.nextInt();
}
for (int i = 0; i < n - 1; i++) {
int s = sc.nextInt() - 1;
int t = sc.nextInt() - 1;
tree[s].add(t);
tree[t].add(s);
}
long cnt = 0;
for (int i = 0; i < n; i++) {
v = new boolean[n];
cnt = (cnt + dfs(i, i)) % MOD;
}
System.out.println(cnt);
}
long dfs(int u, int root) {
v[u] = true;
long res = 1;
for (int next : tree[u]) {
if (!v[next]) {
if (a[next] < a[root] || a[next] > a[root] + d) continue;
if (a[next] == a[root] && next < root) continue;
res = (res * (dfs(next, root) + 1)) % MOD;
}
}
return res;
}
public static void main(String[] args) {
new tmp().run();
}
} | Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | 8789ceade7ac0d807b3df6f4addf6ba2 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class D_277 {
MyScanner sc = new MyScanner();
final int MOD = 1000000007;
int d, n;
int[] a, f;
ArrayList<Integer>[] g;
boolean[] v;
@SuppressWarnings("unchecked")
void run() {
d = sc.nextInt();
n = sc.nextInt();
a = sc.nextIntArray(n);
f = new int[n];
v = new boolean[n];
g = new ArrayList[n];
for (int i = 0; i < n; i++)
g[i] = new ArrayList<Integer>();
for (int i = 0; i < n - 1; i++) {
int s = sc.nextInt() - 1;
int t = sc.nextInt() - 1;
g[s].add(t);
g[t].add(s);
}
int result = 0;
for (int i = 0; i < n; i++) {
Arrays.fill(v, false);
Arrays.fill(f, 0);
dfs(i, i);
result = (result + f[i]) % MOD;
}
System.out.println(result);
}
void dfs(int u, int root) {
v[u] = true;
f[u] = 1;
for (int next : g[u]) {
if (!v[next]) {
if (a[next] < a[root] || a[next] > a[root] + d) continue;
if (a[next] == a[root] && next < root) continue;
dfs(next, root);
f[u] = (int)(((long)f[u] * (f[next] + 1)) % MOD);
}
}
}
public static void main(String[] args) {
new D_277().run();
}
void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
void debug2(char[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
}
boolean inner(int h, int w, int limH, int limW) {
return 0 <= h && h < limH && 0 <= w && w < limW;
}
void swap(int[] x, int a, int b) {
int tmp = x[a];
x[a] = x[b];
x[b] = tmp;
}
// find minimum i (a[i] >= border)
int lower_bound(int a[], int border) {
int l = -1;
int r = a.length;
while (r - l > 1) {
int mid = (l + r) / 2;
if (border <= a[mid]) {
r = mid;
} else {
l = mid;
}
}
// r = l + 1
return r;
}
boolean palindrome(String s) {
for (int i = 0; i < s.length() / 2; i++) {
if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
return false;
}
}
return true;
}
class MyScanner {
int nextInt() {
try {
int c = System.in.read();
while (c != '-' && (c < '0' || '9' < c))
c = System.in.read();
if (c == '-')
return -nextInt();
int res = 0;
do {
res *= 10;
res += c - '0';
c = System.in.read();
} while ('0' <= c && c <= '9');
return res;
} catch (Exception e) {
return -1;
}
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String next() {
try {
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while (Character.isWhitespace(c))
c = System.in.read();
do {
res.append((char) c);
} while (!Character.isWhitespace(c = System.in.read()));
return res.toString();
} catch (Exception e) {
return null;
}
}
int[] nextIntArray(int n) {
int[] in = new int[n];
for (int i = 0; i < n; i++) {
in[i] = nextInt();
}
return in;
}
int[][] nextInt2dArray(int n, int m) {
int[][] in = new int[n][m];
for (int i = 0; i < n; i++) {
in[i] = nextIntArray(m);
}
return in;
}
double[] nextDoubleArray(int n) {
double[] in = new double[n];
for (int i = 0; i < n; i++) {
in[i] = nextDouble();
}
return in;
}
long[] nextLongArray(int n) {
long[] in = new long[n];
for (int i = 0; i < n; i++) {
in[i] = nextLong();
}
return in;
}
char[][] nextCharField(int n, int m) {
char[][] in = new char[n][m];
for (int i = 0; i < n; i++) {
String s = sc.next();
for (int j = 0; j < m; j++) {
in[i][j] = s.charAt(j);
}
}
return in;
}
}
} | Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | b6814d169154ceb83ba922c72f5be8d0 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
public class Solution{
///////////////////////////////////////////////////////////////////////////
static class FastScanner{
BufferedReader s;
StringTokenizer st;
public FastScanner(InputStream InputStream){
st = new StringTokenizer("");
s = new BufferedReader(new InputStreamReader(InputStream));
}
public FastScanner(File f) throws FileNotFoundException{
st = new StringTokenizer("");
s = new BufferedReader (new FileReader(f));
}
public int nextInt() throws IOException{
if(st.hasMoreTokens())
return Integer.parseInt(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextInt();
}
}
/* public double nextDouble() throws IOException{
if(st.hasMoreTokens())
return Double.parseDouble(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextDouble();
}
}
*/
public long nextLong() throws IOException{
if(st.hasMoreTokens())
return Long.parseLong(st.nextToken());
else{
st = new StringTokenizer(s.readLine());
return nextLong();
}
}
public String nextString() throws IOException{
if(st.hasMoreTokens())
return st.nextToken();
else{
st = new StringTokenizer(s.readLine());
return nextString();
}
}
public String readLine() throws IOException{
return s.readLine();
}
public void close() throws IOException{
s.close();
}
}
////////////////////////////////////////////////////////////////////
// Number Theory
long pow(long a,long b,long mod){
long x = 1; long y = a;
while(b > 0){
if(b % 2 == 1){
x = (x*y);
x %= mod;
}
y = (y*y);
y %= mod;
b /= 2;
}
return x;
}
int divisor(long x,long[] a){
long limit = x;
int numberOfDivisors = 0;
for (int i=1; i < limit; ++i) {
if (x % i == 0) {
limit = x / i;
if (limit != i) {
numberOfDivisors++;
}
numberOfDivisors++;
}
}
return numberOfDivisors;
}
void findSubsets(int array[]){
long numOfSubsets = 1 << array.length;
for(int i = 0; i < numOfSubsets; i++){
int pos = array.length - 1;
int bitmask = i;
while(bitmask > 0){
if((bitmask & 1) == 1)
ww.print(array[pos]+" ");
bitmask >>= 1;
pos--;
}
ww.println();
}
}
public static long gcd(long a, long b){
return b == 0 ? a : gcd(b,a%b);
}
public static int lcm(int a,int b, int c){
return lcm(lcm(a,b),c);
}
public static int lcm(int a, int b){
return (int) (a*b/gcd(a,b));
}
////////////////////////////////////////////////////////////////////
// private static FastScanner s = new FastScanner(new File("input.txt"));
// private static PrintWriter ww = new PrintWriter(new FileWriter("output.txt"));
static InputStream inputStream = System.in;
static FastScanner s = new FastScanner(inputStream);
static OutputStream outputStream = System.out;
static PrintWriter ww = new PrintWriter(new OutputStreamWriter(outputStream));
// private static Scanner s = new Scanner(System.in);
@SuppressWarnings("unused")
private static int[][] states = { {-1,0} , {1,0} , {0,-1} , {0,1} };
////////////////////////////////////////////////////////////////////
public static void main(String[] args) throws IOException{
new Solution().solve();
s.close();
ww.close();
}
////////////////////////////////////////////////////////////////////
int MAXN = 2000 + 10;
int MOD = (int)(1e9) + 7;
@SuppressWarnings("unchecked")
ArrayList<Integer>[] adj = new ArrayList[MAXN];
int[] a = new int[MAXN];
long[] f = new long[MAXN];
boolean[] visited = new boolean[MAXN];
int d,n;
void DFS(int u, int root) {
visited[u] = true;
f[u] = 1;
for(int v : adj[u]) {
if (!visited[v]) {
if ((a[v] < a[root]) || (a[v] > a[root] + d)) continue;
if ((a[v] == a[root]) && (v < root)) continue; // avoid duplicate counting
DFS(v, root);
f[u] = ((long)(f[u]) * (f[v] + 1)) % MOD;
}
}
}
void solve() throws IOException{
d = s.nextInt();
n = s.nextInt();
for(int i=1;i<=n;i++) a[i] = s.nextInt();
for(int i=0;i<adj.length;i++) adj[i] = new ArrayList<Integer>();
for(int i=1;i<=n-1;i++){
int u = s.nextInt();
int v = s.nextInt();
adj[u].add(v);
adj[v].add(u);
}
long result = 0;
for(int i = 1; i <= n; i++) {
Arrays.fill(visited, false);
Arrays.fill(f, 0);
DFS(i, i);
// ww.println(f[i]);
result = (result + f[i]) % MOD;
}
ww.println(result);
}
} | Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | 1c55f44bf62f94e541f324ecbbfe80d8 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main{
// ArrayList<Integer> lis = new ArrayList<Integer>();
// ArrayList<String> lis = new ArrayList<String>();
// PriorityQueue<P> que = new PriorityQueue<P>();
// PriorityQueue<Integer> que = new PriorityQueue<Integer>();
// Stack<Integer> que = new Stack<Integer>();
//HashMap<Long,Long> map = new HashMap<Long,Long>();
// static long sum=0;
// 1000000007 (10^9+7)
static int mod = 1000000007;
//static int mod = 1000000009; ArrayList<Integer> l[]= new ArrayList[n];
static int dx[]={1,-1,0,0};
static int dy[]={0,0,1,-1};
// static int dx[]={1,-1,0,0,1,1,-1,-1};
// static int dy[]={0,0,1,-1,1,-1,1,-1};
//static Set<Integer> set = new HashSet<Integer>();
//static ArrayList<Integer> l[];
//static int parent[][],depth[],node,max_log;
static ArrayList<Integer> nd[]= new ArrayList[2001];
public static void main(String[] args) throws Exception, IOException{
//Scanner sc =new Scanner(System.in);
Reader sc = new Reader(System.in);
//int a=sc.nextInt(),b=sc.nextInt(),c=sc.nextInt(),d=sc.nextInt(),r=sc.nextInt();
//int n=sc.nextInt();//,m=sc.nextInt(),k=sc.nextInt();
//int a=sc.nextInt(),b=sc.nextInt(),c=sc.nextInt();
//double d[]=new double[100];
int d=sc.nextInt(),n=sc.nextInt();//,k=sc.nextInt(),s=0;
// int a[]=new int[n];
boolean u[]=new boolean[n];
for (int i = 0; i < u.length; i++) {
nd[i]=new ArrayList<Integer>();
nd[i].add(sc.nextInt());
}
for (int i = 0; i < n-1; i++) {
int x=sc.nextInt()-1;
int y=sc.nextInt()-1;
nd[x].add(y); nd[y].add(x);
}
long r=0;
for (int i = 0; i < u.length; i++) {
u[i]=true;
r+=dfs(i,d,nd[i].get(0),-1,u);
r%=mod;
}
System.out.println(r);
}
static long dfs(int x,int d,int mx,int pr,boolean u[]){
long r=1;
for (int i = 1; i < nd[x].size(); i++) {
int y=nd[x].get(i),z=nd[y].get(0);
if(z>mx || mx-z>d ||y==pr)continue;
if( mx==z && u[y])continue;
r*=dfs(y,d,mx,x,u)+1;
r%=mod;
}
return r;
}
/*
static class P implements Comparable<P>{
int id, d; ;
P(int id,int d){
this.id=id;
this.d=d;
}
public int compareTo(P x){
// return (-x.d+d)>=0?1:-1 ; // ascend long
// return -x.d+d ; // ascend
return x.d-d ; //descend
}
}//*/
static void db(Object... os){
System.err.println(Arrays.deepToString(os));
}
static boolean validpos(int x,int y,int r, int c){
return x<r && 0<=x && y<c && 0<=y;
}
static boolean bit(int x,int k){
// weather k-th bit (from right) be one or zero
return ( 0 < ( (x>>k) & 1 ) ) ? true:false;
}
}
class Reader
{
private BufferedReader x;
private StringTokenizer st;
public Reader(InputStream in)
{
x = new BufferedReader(new InputStreamReader(in));
st = null;
}
public String nextString() throws IOException
{
while( st==null || !st.hasMoreTokens() )
st = new StringTokenizer(x.readLine());
return st.nextToken();
}
public int nextInt() throws IOException
{
return Integer.parseInt(nextString());
}
public long nextLong() throws IOException
{
return Long.parseLong(nextString());
}
public double nextDouble() throws IOException
{
return Double.parseDouble(nextString());
}
} | Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | a240f853df716ad928f12d40f7a2759b | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class ProblemD {
BufferedReader rd;
private ProblemD() throws IOException {
rd = new BufferedReader(new InputStreamReader(System.in));
compute();
}
private void compute() throws IOException {
int[] a = intarr();
int d = a[0];
int n = a[1];
a = intarr();
for(int i=0;i<a.length;i++) {
a[i] *= 10000;
a[i] += i+1;
}
d = d*10000 + 4999;
List<List<Integer>> e = new ArrayList<>();
for(int i=0;i<n;i++) {
e.add(new ArrayList<Integer>());
}
for(int i=0;i<n-1;i++) {
int[] uv = intarr();
uv[0]--;
uv[1]--;
e.get(uv[0]).add(uv[1]);
e.get(uv[1]).add(uv[0]);
}
final long B = 1000000007L;
long res = 0;
for(int i=0;i<n;i++) {
int mc = a[i];
int mx = a[i] + d;
boolean[] visited = new boolean[n];
visited[i] = true;
int[] q = new int[n*2];
int head = 0;
int tail = 0;
q[tail++] = i;
while(head != tail) {
int u = q[head++];
for(Integer v: e.get(u)) {
if(!visited[v]) {
visited[v] = true;
if(a[v] >= mc && a[v] <= mx) {
q[tail++] = v;
}
}
}
}
long[] c = new long[n];
boolean[] vt = new boolean[n];
for(int j=tail-1;j>=0;j--) {
int u = q[j];
vt[u] = true;
boolean found = false;
long x = 1;
for(Integer v: e.get(u)) {
if(vt[v]) {
found = true;
long p = c[v];
p++;
p %= B;
x *= p;
x %= B;
}
}
if(found) {
c[u] = x;
c[u] %= B;
} else {
c[u] = 1;
}
}
res += c[i];
res %= B;
}
out(res);
}
private int pint() throws IOException {
return pint(rd.readLine());
}
private int pint(String s) {
return Integer.parseInt(s);
}
private int[] intarr() throws IOException {
return intarr(rd.readLine());
}
private int[] intarr(String s) {
String[] q = s.split(" ");
int n = q.length;
int[] a = new int[n];
for(int i=0;i<n;i++) {
a[i] = Integer.parseInt(q[i]);
}
return a;
}
private long plong() throws IOException {
return plong(rd.readLine());
}
private long plong(String s) {
return Long.parseLong(s);
}
private long[] longarr() throws IOException {
return longarr(rd.readLine());
}
private long[] longarr(String s) {
String[] q = s.split(" ");
int n = q.length;
long[] a = new long[n];
for(int i=0;i<n;i++) {
a[i] = Long.parseLong(q[i]);
}
return a;
}
private static void out(Object x) {
System.out.println(x);
}
public static void main(String[] args) throws IOException {
new ProblemD();
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | f1a59766c5145d6fea1d87420b8b1d00 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main implements Runnable {
// leave empty to read from stdin/stdout
private static final String TASK_NAME_FOR_IO = "";
// file names
private static final String FILE_IN = TASK_NAME_FOR_IO + ".in";
private static final String FILE_OUT = TASK_NAME_FOR_IO + ".out";
BufferedReader in;
PrintWriter out;
StringTokenizer tokenizer = new StringTokenizer("");
public static void main(String[] args) {
new Thread(new Main()).start();
}
int n, d;
List<Integer> []g;
int []a;
boolean []used;
long []dp;
final static long MOD = (long)(1e9) + 7;
private void solve() throws IOException {
d = nextInt();
n = nextInt();
g = new LinkedList[n];
for(int i = 0; i < n; ++i) g[i] = new LinkedList<Integer>();
a = new int[n];
for(int i = 0; i < n; ++i) a[i] = nextInt();
for(int i = 0; i + 1 < n; ++i) {
int v = nextInt()-1, u = nextInt()-1;
g[v].add(u);
g[u].add(v);
}
dp = new long[n];
used = new boolean[n];
long ret = 0;
for(int i = 0; i < n; ++i) {
Arrays.fill(dp, 0);
Arrays.fill(used, false);
dfs(i, i);
ret = (ret + dp[i]) % MOD;
// System.out.println(i + " " + dp[i]);
}
out.println(ret);
}
private void dfs(int x, int root) {
used[x] = true;
dp[x] = 1;
for(int i : g[x]) {
if (used[i]) continue;
if (a[i] < a[root] || a[i] > a[root] + d) continue;
if (a[i] == a[root] && i < root) continue;
dfs(i, root);
dp[x] = dp[x] * (dp[i] + 1);
dp[x] %= MOD;
}
}
public void run() {
long timeStart = System.currentTimeMillis();
boolean fileIO = TASK_NAME_FOR_IO.length() > 0;
try {
if (fileIO) {
in = new BufferedReader(new FileReader(FILE_IN));
out = new PrintWriter(new FileWriter(FILE_OUT));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
}
solve();
in.close();
out.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
long timeEnd = System.currentTimeMillis();
if (fileIO) {
System.out.println("Time spent: " + (timeEnd - timeStart) + " ms");
}
}
private String nextToken() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private BigInteger nextBigInt() throws IOException {
return new BigInteger(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | f4b1d5ac3d19d47790ebba271cded7f2 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
import javax.jws.soap.SOAPBinding.Use;
public class D {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
static int d;
static ArrayList<Integer>[]ages;
static long[]dp;
static boolean[][]f;
static class Sort implements Comparable<Sort> {
int val, ind;
public int compareTo(Sort arg0) {
return this.val-arg0.val;
}
}
static boolean[]used;
static int mod = (int) (1e9+7);
static int min, from;
static int[]a;
static long ans;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
d = nextInt();
int n = nextInt();
Sort[]b = new Sort[n+1];
ages = new ArrayList[n+1];
a = new int[n+1];
f = new boolean[n+1][n+1];
for (int i = 1; i <= n; i++) {
b[i] = new Sort();
b[i].val = nextInt();
b[i].ind = i;
a[i] = b[i].val;
ages[i] = new ArrayList<>();
}
Arrays.sort(b, 1, n+1);
for (int i = 1; i < n; i++) {
int v = nextInt();
int u = nextInt();
ages[v].add(u);
ages[u].add(v);
}
used = new boolean[2001];
dp = new long[n+1];
for (int i = 1; i <= n; i++) {
min = b[i].val;
Arrays.fill(dp, 1);
from = b[i].ind;
dfs(b[i].ind, 0);
ans = (ans+dp[b[i].ind]) % mod;
}
for (int i = 1; i <= n; i++) {
if (used[i]) {
ans = (ans+1) % mod;
}
}
System.out.println(ans);
pw.close();
}
private static void dfs(int v, int p) {
f[from][v] = true;
for (int to : ages[v]) {
if (to==p || a[to] < min || a[to] > min+d)
continue;
if (a[to]==min && f[to][from]) {
continue;
}
dfs(to, v);
dp[v] = dp[v] * (dp[to]+1) % mod;
}
}
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st==null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | 64b5045a8722bac1dc844171c30e6c8d | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.util.*;
import java.io.*;
public class D {
public static PrintStream out = System.out;
public static InputReader in = new InputReader(System.in);
static long MOD = 1000000007;
static int D, N;
static int[] a;
static boolean[] marked;
static List<List<Integer>> adj;
public static void main(String args[]) {
D = in.nextInt();
N = in.nextInt();
a = new int[N];
adj = new ArrayList<>();
for (int i = 0; i < N; i++) {
a[i] = in.nextInt();
}
for (int i = 0; i < N; i++) {
adj.add(new ArrayList<Integer>());
}
for (int i = 0; i < N - 1; i++) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
adj.get(u).add(v);
adj.get(v).add(u);
}
long tot = 0;
marked = new boolean[N];
for (int i = 0; i < N; i++) {
tot += f(i, i);
tot %= MOD;
}
out.println(tot);
}
static long f(int v, int root) {
long ret = 1;
marked[v] = true;
for (int u : adj.get(v)) {
if (!marked[u]) {
// out.println(u + " " + root);
if (a[u] > a[root] + D || a[u] < a[root]) continue;
if (a[u] == a[root] && root < u) continue;
ret *= 1 + f(u, root);
ret %= MOD;
}
}
marked[v] = false;
// out.println(v + " " + root + " " + ret);
return ret;
}
}
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 double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | addd6996cb1a929adab9e8311eeb784a | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes |
import java.util.*;
import java.io.*;
public class ValidSets486D {
static int P = (int) 1e9 + 7;
static List<Integer>[] tree = null;
static int[] wt = null;
static boolean[] visited = null;
static int d = 0;
static void go() {
d = in.nextInt();
int n = in.nextInt();
wt = new int[n];
int[][] nwt = new int[n][2];
for (int i = 0; i < n; i++) {
wt[i] = in.nextInt();
nwt[i][0] = i;
nwt[i][1] = wt[i];
}
tree = new List[n];
for (int i = 0; i < n; i++)
tree[i] = new ArrayList<Integer>();
for (int i = 0; i < n - 1; i++) {
int from = in.nextInt() - 1;
int to = in.nextInt() - 1;
tree[from].add(to);
tree[to].add(from);
}
Arrays.sort(nwt, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[1] - o2[1];
}
});
visited = new boolean[n];
long count = 0;
for (int[] node : nwt) {
visited[node[0]] = true;
count += dfs(node[0], node[1]);
}
out.println(count % P);
}
static long dfs(int from, int min) {
long ret = 1;
for (int next : tree[from]) {
if (!visited[next] && wt[next] <= min + d && wt[next] >= min) {
visited[next] = true;
ret *= 1 + dfs(next, min);
ret %= P;
visited[next] = false;
}
}
return ret;
}
static InputReader in;
static PrintWriter out;
public static void main(String[] args) {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
go();
out.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int[] nextIntArray(int len) {
int[] ret = new int[len];
for (int i = 0; i < len; i++)
ret[i] = nextInt();
return ret;
}
public long[] nextLongArray(int len) {
long[] ret = new long[len];
for (int i = 0; i < len; i++)
ret[i] = nextLong();
return ret;
}
public int nextInt() {
return (int) nextLong();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder sb = new StringBuilder(1024);
do {
sb.append((char) c);
c = read();
} while (!isSpaceChar(c));
return sb.toString();
}
public static boolean isSpaceChar(int c) {
switch (c) {
case -1:
case ' ':
case '\n':
case '\r':
case '\t':
return true;
default:
return false;
}
}
}
} | Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | 641ee72ce92412f72c4de38fa6e7c85b | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class R277qDValidSets {
static int n,d;
static ArrayList<Integer> g[];
static int a[];
static long mod = (long)(1e9 + 7);
@SuppressWarnings("unchecked")
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter w = new PrintWriter(System.out);
StringTokenizer st1 = new StringTokenizer(br.readLine());
d = ip(st1.nextToken());
n = ip(st1.nextToken());
StringTokenizer st2 = new StringTokenizer(br.readLine());
a = new int[n];
for(int i=0;i<n;i++)
a[i] = ip(st2.nextToken());
g = new ArrayList[n];
for(int i=0;i<n;i++)
g[i] = new ArrayList<Integer>();
for(int i=1;i<n;i++){
StringTokenizer st = new StringTokenizer(br.readLine());
int u = ip(st.nextToken()) - 1;
int v = ip(st.nextToken()) - 1;
g[u].add(v);
g[v].add(u);
}
long ans = 0;
for(int i=0;i<n;i++){
ans += dfs(i,-1,i) + mod - 1;
if(ans >= mod) ans %= mod;
}
w.println(ans);
w.close();
}
public static long dfs(int curr,int prev,int minID){
if(a[curr] < a[minID]) return 1;
if(a[curr] == a[minID] && curr < minID) return 1;
if(a[curr] > a[minID] + d) return 1;
long ret = 1;
int s = g[curr].size();
for(int i=0;i<s;i++){
if(g[curr].get(i) == prev) continue;
ret *= dfs(g[curr].get(i),curr,minID);
if(ret >= mod) ret %= mod;
}
return ret + 1;
}
public static int ip(String s){
return Integer.parseInt(s);
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | de61196bd5a00013a0f309bae657a705 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;
public class R277D2D {
static final int MOD = (int)1e9+7;
static int[] cursor, edges, a;
static boolean[] visited, checked;
static int d;
static int count(int i, int max){
long ret = 1;
visited[i] = true;
for(int e=cursor[i]; e<cursor[i+1]; e++){
int j = edges[e];
if(!checked[j] && !visited[j] && max>=a[j] && max-a[j]<=d){
ret = (ret*(count(j, max)+1))%MOD;
}
}
return (int)ret;
}
static class Node implements Comparable<Node>{
int index; int value;
public Node(int index, int value){
this.index = index;
this.value = value;
}
@Override
public int compareTo(Node o) {
return o.value-this.value;
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
d = Integer.parseInt(st.nextToken());
int n = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
a = new int[n];
for(int i=0; i<n; i++){
a[i] = Integer.parseInt(st.nextToken());
}
cursor = new int[n+1];
int[] x = new int[n-1];
int[] y = new int[n-1];
for(int i=0; i<n-1; i++){
st = new StringTokenizer(br.readLine());
x[i] = Integer.parseInt(st.nextToken())-1;
y[i] = Integer.parseInt(st.nextToken())-1;
cursor[x[i]]++;
cursor[y[i]]++;
}
for(int i=0; i<n; i++) cursor[i+1] += cursor[i];
edges = new int[2*(n-1)];
for(int i=0; i<n-1; i++){
edges[--cursor[x[i]]] = y[i];
edges[--cursor[y[i]]] = x[i];
}
Node[] nodes = new Node[n];
for(int i=0; i<n; i++){
nodes[i] = new Node(i, a[i]);
}
Arrays.sort(nodes);
visited = new boolean[n];
checked = new boolean[n];
int ret = 0;
for(int i=0; i<n; i++){
Arrays.fill(visited, false);
ret = (ret + count(nodes[i].index, nodes[i].value))%MOD;
checked[nodes[i].index] = true;
}
System.out.println(ret);
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | b9fe4fa0542e5e0f66eab80bbbd03db4 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.util.*;
public class ValidSets
{
static ArrayList<ArrayList<Integer>> adjList = new ArrayList<ArrayList<Integer>>();
static long VAL[] = new long [2050];
static long DP[] = new long [2050];
static long ans =0, MOD = 1000000007;
static long D;
static int N;
public static void main(String[]args)
{
InputReader1 sc = new InputReader1(System.in);
for(int i=0;i<=2050;i++)adjList.add(new ArrayList<Integer>());
D = sc.nextLong() ;
N = sc.nextInt();
for(int i=1;i<=N;i++)
VAL[i] = sc.nextLong();
for(int i=1;i<N;i++)
{
int u = sc.nextInt() , v = sc.nextInt();
adjList.get(u).add(v);
adjList.get(v).add(u);
}
for(int i=1;i<=N;i++)
{
Arrays.fill(DP,0);
dfs(i,i,-1);
ans += DP[i];
ans %= MOD;
}
System.out.println(ans);
}
static void dfs(int root , int node , int par)
{
DP[node] = 1;
for(int next:adjList.get(node))
{
if(next==par)continue;
if((VAL[next] < VAL[root])|| (VAL[next] > VAL[root] +D))continue;
// Prevent overcounting
if((VAL[next] == VAL[root] && next<root))continue;
dfs(root,next,node);
DP[node] = (DP[node]*(DP[next]+1)) % MOD;
}
}
}
class InputReader1
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader1(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int 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 & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
//while (c != '\n' && c != '\r' && c != '\t' && c != -1)
//c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (c != '\n' && c != '\r' && c != '\t' && c != -1);
return res.toString();
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | 4531b6e2da2c761736394e3975b59083 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Kyujin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
MyInputReader in = new MyInputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
int maxn = 2200;
static final int mod = 1000000007;
ArrayList<Integer>[] tree = new ArrayList[maxn];
long[] a = new long[maxn];
long[] count = new long[maxn];
boolean[] visited = new boolean[maxn];
int d, n;
public void solve(int testNumber, MyInputReader in, PrintWriter out) {
d = in.readInt();
n = in.readInt();
for(int i=1; i<=n; i++) {
a[i] = in.readInt();
tree[i] = new ArrayList<>();
}
for(int i=1; i<=n-1; i++){
int u = in.readInt();
int v = in.readInt();
tree[u].add(v);
tree[v].add(u);
}
long result = 0;
for(int i=1; i <= n; i++){
for(int j=1; j<=n; j++){
count[j] = 0;
visited[j] = false;
}
visit(i, i);
result = (result + count[i]) % mod;
}
out.println(result);
}
void visit(int node, int root){
visited[node] = true;
count[node] = 1;
for(int i=0; i< tree[node].size(); i++){
int v = tree[node].get(i);
if(!visited[v]){
if((a[v] < a[root] || a[v] > a[root] + d)) continue;
if((a[v] == a[root]) && (v < root)) continue;
visit(v, root);
count[node] = (count[node] * (count[v] + 1))%mod;
}
}
}
}
class MyInputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public MyInputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
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;
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | 26eb77267809fc0827b4b7272dcfb87f | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.util.*;
public class d {
static ArrayList<Integer>[] g, tree;
static int[] vals;
static int d;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
d = input.nextInt(); int n = input.nextInt();
g = new ArrayList[n]; tree = new ArrayList[n];
for(int i = 0; i<n; i++)
{
g[i] = new ArrayList<Integer>();
tree[i] = new ArrayList<Integer>();
}
vals = new int[n];
int max = 0;
for(int i = 0; i<n; i++) max = Math.max(max, vals[i] = input.nextInt());
for(int i = 0; i<n-1; i++)
{
int a = input.nextInt()-1, b = input.nextInt()-1;
g[a].add(b);
g[b].add(a);
}
boolean[] vis = new boolean[n];
vis[0] = true;
Queue<Integer> q = new LinkedList<Integer>();
q.add(0);
while(!q.isEmpty())
{
int at = q.poll();
for(int e: g[at])
{
if(vis[e]) continue;
vis[e] = true;
q.add(e);
tree[at].add(e);
}
}
g = null;
memo = new int[2][n][2001];
for(int[][] A: memo)
for(int[] B: A)
Arrays.fill(B, -1);
long res = 0;
for(int root = 0; root < n; root++)
for(int i = 1; i<=max; i++)
{
res = (res + go(root, i, 1))%mod;
//System.out.println(root+" "+i+" "+res);
}
System.out.println(res);
}
static int[][][] memo;
static long mod = 1000000007;
static int go(int at, int min, int flag)
{
//System.out.println((at+1)+" "+min+" "+flag);
if(memo[flag][at][min] != -1) return memo[flag][at][min];
if(Math.abs(min - vals[at]) > d) return memo[flag][at][min] = 0;
if(vals[at] < min) return memo[flag][at][min] = 0;
if(flag == 0 && vals[at] == min) return memo[flag][at][min] = 0;
if(tree[at].size() == 0)
{
if(flag == 1 && vals[at] != min) return memo[flag][at][min] = 0;
return memo[flag][at][min] = 1;
}
if(flag == 0)
{
long res = 1;
for(int e: tree[at])
{
res = (res * (1+go(e, min, 0)))%mod;
}
return memo[flag][at][min] = (int)res;
}
else
{
long res = 1;
if(vals[at] == min)
{
for(int e : tree[at])
{
res = (res * (1 + go(e, min, 1) + go(e, min, 0)))%mod;
}
}
else
{
res = 0;
ArrayList<Integer> children = tree[at];
long[] anything = new long[children.size()];
for(int i = 0; i<children.size(); i++)
{
int child = children.get(i);
anything[i] = 1 + go(child, min, 1) + go(child, min, 0);
}
for(int i = children.size()-2; i>=0; i--) anything[i] = (anything[i] * anything[i+1])%mod;
long allZeroes = 1;
for(int i = 0; i<children.size(); i++)
{
int child = children.get(i);
long toAdd = (allZeroes * (i == children.size() - 1 ? 1 : anything[i+1]))%mod;
toAdd = (toAdd * go(child, min, 1))%mod;
res = (res + toAdd)%mod;
allZeroes = (allZeroes * (1+go(child, min, 0)))%mod;
}
}
return memo[flag][at][min] = (int)res;
}
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | e4db52a0a8bb61950c1a46862cab3ed2 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class D {
static class Scanner{
BufferedReader br=null;
StringTokenizer tk=null;
public Scanner(){
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException{
while(tk==null || !tk.hasMoreTokens())
tk=new StringTokenizer(br.readLine());
return tk.nextToken();
}
public int nextInt() throws NumberFormatException, IOException{
return Integer.valueOf(next());
}
public long nextLong() throws NumberFormatException, IOException{
return Long.valueOf(next());
}
public double nextDouble() throws NumberFormatException, IOException{
return Double.valueOf(next());
}
}
static int mod = 1000000007;
static class Node{
int value;
int id;
LinkedList<Integer> v;
public Node(int vv, int ii){
value = vv;
id = ii;
v = new LinkedList<Integer>();
}
}
static int f(int node, int papa, int ref){
int ret = 1;
for(int h: array[node].v){
if (h == papa) continue;
if (array[h].value < array[ref].value) continue;
if (array[h].value == array[ref].value && array[h].id < array[ref].id) continue;
if (array[h].value - array[ref].value > D) continue;
ret = (int)((ret * (1L + f(h, node, ref))) % mod);
}
return ret;
}
static int D, N;
static Node[] array;
public static void main(String args[]) throws NumberFormatException, IOException{
Scanner sc = new Scanner();
D = sc.nextInt();
N = sc.nextInt();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
array = new Node[N];
for(int i = 0; i < N; i++){
int value = sc.nextInt();
if (!map.containsKey(value))
map.put(value, 0);
else
map.put(value, map.get(value) + 1);
array[i] = new Node(value, map.get(value));
}
for(int i = 0; i < N - 1; i++){
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
array[a].v.add(b);
array[b].v.add(a);
}
int ans = 0;
for(int i = 0; i < N; i++)
ans = (ans + f(i, -1, i)) % mod;
System.out.println(ans);
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | e22f2ac081cdf5c81b7494644595ea0b | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.Vector;
public class ValidSets {
public static void main(String[] args) throws IOException {
ValidSetsSolver solver = new ValidSetsSolver();
solver.read();
solver.solve();
}
}
class ValidSetsSolver {
private final Integer MAXN = 2048;
private final Long MOD = 1000000007L;
private InputReader input;
private PrintWriter output;
private Integer d, n;
private Vector < Integer > [] v;
private Integer[] a;
private Long[] dp;
private Boolean[] used;
ValidSetsSolver() {
input = new InputReader ( System.in );
output= new PrintWriter ( System.out );
}
private void initialize() {
a = new Integer[MAXN];
v = new Vector[MAXN];
dp = new Long[MAXN];
used = new Boolean[MAXN];
for ( int i = 1; i <= n; ++ i ) {
v[i] = new Vector < Integer >();
}
}
public void read() throws IOException {
d = input.nextInt();
n = input.nextInt();
initialize();
for ( int i = 1; i <= n; ++ i ) {
a[i] = input.nextInt();
}
Integer x, y;
for ( int i = 0; i < n - 1; ++ i ) {
x = input.nextInt();
y = input.nextInt();
v[x].add(y);
v[y].add(x);
}
input.close();
}
private Long dfs ( Integer i, Integer root ) {
Integer size = v[i].size();
dp[i] = 1L;
used[i] = true;
for ( int j = 0; j < size; ++ j ) {
Integer nextVertex = v[i].get(j);
if ( a[nextVertex].intValue() < a[root].intValue() || a[root] < a[nextVertex] - d ) continue;
if ( a[nextVertex].intValue() == a[root].intValue() && nextVertex.intValue() < root.intValue() ) continue;
if ( used[ nextVertex ] == false ) {
dp[i] *= ( dfs ( nextVertex, root ) + 1L );
if ( dp[i] > MOD ) dp[i] %= MOD;
}
}
return dp[i];
}
public void solve() {
Long answer = new Long(0);
for ( int i = 1; i <= n; ++ i ) {
resetArray();
answer += dfs ( i, i );
if ( answer > MOD ) answer %= MOD;
}
output.println ( answer );
output.close();
}
private void resetArray() {
for ( int i = 0; i < MAXN; ++ i ) {
dp[i] = 0L;
used[i] = false;
}
}
}
class InputReader {
private BufferedReader input;
private StringTokenizer tokenizer;
public InputReader ( InputStream stream ) {
input = new BufferedReader ( new InputStreamReader ( stream ), 32768 );
tokenizer = null;
}
public void close() throws IOException {
try {
input.close();
}
catch ( IOException error ) {
throw new RuntimeException ( error );
}
}
public String next () {
while ( tokenizer == null || !tokenizer.hasMoreTokens() ) {
try {
tokenizer = new StringTokenizer ( input.readLine() );
}
catch ( IOException error ) {
throw new RuntimeException ( error );
}
}
return tokenizer.nextToken();
}
public Integer nextInt() {
return Integer.parseInt( next() );
}
public Double nextDouble() {
return Double.parseDouble ( next() );
}
public Long nextLong() {
return Long.parseLong( next() );
}
public String nextString() {
return next();
}
public Boolean nextBool() {
return Boolean.parseBoolean( next() );
}
} | Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | b205269d2f26f3d9564d814c591754e2 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.Vector;
public class ValidSets {
public static void main(String[] args) throws IOException {
ValidSetsSolver solver = new ValidSetsSolver();
solver.read();
solver.solve();
}
}
class ValidSetsSolver {
private final int MAXN = 2048;
private final long MOD = 1000000007L;
private InputReader input;
private PrintWriter output;
private int d, n;
private Vector < Integer > [] v;
private int[] a;
private long[] dp;
private boolean[] used;
ValidSetsSolver() {
input = new InputReader ( System.in );
output= new PrintWriter ( System.out );
}
private void initialize() {
a = new int[MAXN];
v = new Vector[MAXN];
dp = new long[MAXN];
used = new boolean[MAXN];
for ( int i = 1; i <= n; ++ i ) {
v[i] = new Vector < Integer >();
}
}
public void read() throws IOException {
d = input.nextInt();
n = input.nextInt();
initialize();
for ( int i = 1; i <= n; ++ i ) {
a[i] = input.nextInt();
}
Integer x, y;
for ( int i = 0; i < n - 1; ++ i ) {
x = input.nextInt();
y = input.nextInt();
v[x].add(y);
v[y].add(x);
}
input.close();
}
private long dfs ( int i, int root ) {
int size = v[i].size();
dp[i] = 1L;
used[i] = true;
for ( int j = 0; j < size; ++ j ) {
int nextVertex = v[i].get(j);
if ( a[nextVertex] < a[root] || a[root] < a[nextVertex] - d ) continue;
if ( a[nextVertex] == a[root] && nextVertex < root ) continue;
if ( used[ nextVertex ] == false ) {
dp[i] *= ( dfs ( nextVertex, root ) + 1L );
if ( dp[i] > MOD ) dp[i] %= MOD;
}
}
return dp[i];
}
public void solve() {
long answer = new Long(0);
for ( int i = 1; i <= n; ++ i ) {
resetArray();
answer += dfs ( i, i );
if ( answer > MOD ) answer %= MOD;
}
output.println ( answer );
output.close();
}
private void resetArray() {
for ( int i = 1; i <= n; ++ i ) {
dp[i] = 0L;
used[i] = false;
}
}
}
class InputReader {
private BufferedReader input;
private StringTokenizer tokenizer;
public InputReader ( InputStream stream ) {
input = new BufferedReader ( new InputStreamReader ( stream ), 32768 );
tokenizer = null;
}
public void close() throws IOException {
try {
input.close();
}
catch ( IOException error ) {
throw new RuntimeException ( error );
}
}
public String next () {
while ( tokenizer == null || !tokenizer.hasMoreTokens() ) {
try {
tokenizer = new StringTokenizer ( input.readLine() );
}
catch ( IOException error ) {
throw new RuntimeException ( error );
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt( next() );
}
public double nextDouble() {
return Double.parseDouble ( next() );
}
public long nextLong() {
return Long.parseLong( next() );
}
public String nextString() {
return next();
}
public Boolean nextBool() {
return Boolean.parseBoolean( next() );
}
} | Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | e1e3cede899effbdac9155a2d7d6b530 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
static long mod = (long)(1e9) + 7;
int n, d, w;
int[] val = new int[2005];
int[] head = new int[2005];
int[] treefrom = new int[2005*2];
int[] treeto = new int[2005*2];
int[] treenext = new int[2005*2];
boolean[][] vis = new boolean [2005][2005];
public long dfs(int root, int now, int fa) {
int i, to;
long ans = 1;
for(i = head[now]; i != -1; i = treenext[i]) {
to = treeto[i];
if(to == fa) continue;
if(Math.abs(val[root] - val[to]) > d) continue;
if(val[to] > val[root]) continue;
if(val[to] < val[root]) {
ans *= dfs(root, to, now)+1;
ans %= mod;
}
else if(val[to] == val[root]){
if(vis[root][to] || vis[to][root]) continue;
vis[root][to]=vis[to][root]=true;
vis[root][to] = vis[to][root] = true;
ans *= dfs(root,to,now)+1;
ans %= mod;
}
}
return ans;
}
public void work() {
d = cin.nextInt();
n = cin.nextInt();
w = 0;
for(int i = 1; i <= n; i ++) {
val[i] = cin.nextInt();
}
for(int i = 1; i <= n; i ++) {
head[i] = -1;
}
for(int i = 1, u, v; i < n; i ++) {
u = cin.nextInt();
v = cin.nextInt();
w++;
treefrom[w]=u;
treeto[w]=v;
treenext[w]=head[u];
head[u]=w;
w++;
treefrom[w]=v;
treeto[w]=u;
treenext[w]=head[v];
head[v]=w;
}
long ans = 0;
for(int i = 1; i <= n; i ++) {
ans += dfs(i, i, 0);
ans %= mod;
}
System.out.println(ans);
}
Main() {
// out = new PrintWriter(System.out);
cin = new Scanner(System.in);
}
public static void main(String[] args) {
Main e = new Main();
e.work();
}
public Scanner cin;
// public PrintWriter out;
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | a910a3a9441d006c3f9e5623904a9690 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.InputMismatchException;
public class D {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
class Pair implements Comparable<Pair> {
int idx, val;
Pair(int idx, int val) {
this.idx = idx;
this.val = val;
}
public int compareTo(Pair s) {
return s.val - val;
}
}
int d, n;
ArrayList<Integer>[] g;
boolean[] visited;
int[] a;
Pair[] p;
int MOD = 1000000007;
int dfs(int u, int prev, int max) {
long res = 1;
for (int v : g[u]) {
if (v == prev || visited[v]) continue;
if (max - a[v] <= d) {
res = (res * (dfs(v, u, max) + 1)) % MOD;
}
}
return (int)res;
}
public void run() {
d = in.nextInt(); n = in.nextInt();
a = in.nextIntArray(n);
p = new Pair[n];
for (int i = 0; i < n; i++) {
p[i] = new Pair(i, a[i]);
}
Arrays.sort(p);
g = new ArrayList[n];
for (int i = 0; i < n; i++) g[i] = new ArrayList<Integer>();
for (int i = 0; i < n - 1; i++) {
int u = in.nextInt() - 1, v = in.nextInt() - 1;
g[u].add(v);
g[v].add(u);
}
visited = new boolean[n];
int res = 0;
for (int i = 0; i < n; i++) {
// System.out.println(p[i].idx + " " + p[i].val);
visited[p[i].idx] = true;
res = (res + dfs(p[i].idx, -1, p[i].val)) % MOD;
// System.out.println("<" + res + " " + i + ">");
}
System.out.println(res);
out.close();
}
public static void main(String[] args) {
new D().run();
}
public void mapDebug(int[][] a) {
System.out.println("--------map display---------");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%3d ", a[i][j]);
}
System.out.println();
}
System.out.println("----------------------------");
System.out.println();
}
public void debug(Object... obj) {
System.out.println(Arrays.deepToString(obj));
}
class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
//stream = new FileInputStream(new File("dec.in"));
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
long nextLong() {
return Long.parseLong(next());
}
long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++)
array[i] = next();
return array;
}
String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | 99357ab0421c9c58646027fa1b0bc041 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | // package Div2;
import java.util.ArrayList;
import java.util.Scanner;
public class CF277 {
private static final int MAXN = 2010;
private static final long MOD = (int)1e9 + 7;
private static ArrayList<Integer>[] adj = new ArrayList[MAXN];
private static int[] a = new int[MAXN];
private static long[] f = new long[MAXN];
private static boolean[] visited = new boolean[MAXN];
private static int d, n;
private static void DFS(int u, int root){
visited[u] = true;
f[u] = 1;
for(int i=0; i<adj[u].size(); i++){
int v = adj[u].get(i);
if(!visited[v]){
if((a[v] < a[root]) || (a[v] > a[root] +d)) continue;
if((a[v] == a[root]) && (v < root)) continue;
DFS(v, root);
f[u] = f[u] * (f[v] + 1) % MOD;
}
}
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
d = input.nextInt();
n = input.nextInt();
for(int i=1; i<=n; i++){
adj[i] = new ArrayList<Integer>();
a[i] = input.nextInt();
}
for(int i=1; i<=n-1; i++){
int u, v;
u = input.nextInt();
v = input.nextInt();
adj[u].add(v);
adj[v].add(u);
}
input.close();
long result = 0;
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
f[j] = 0;
visited[j] = false;
}
DFS(i, i);
result = (result + f[i]) % MOD;
}
System.out.println(result);
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | b6b1fc1099b25faabe28fc9ffd6c32b1 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class SolverD {
public static void main(String[] Args) throws NumberFormatException,
IOException {
new SolverD().Run();
}
PrintWriter pw;
StringTokenizer Stok;
BufferedReader br;
public String nextToken() throws IOException {
while (Stok == null || !Stok.hasMoreTokens()) {
Stok = new StringTokenizer(br.readLine());
}
return Stok.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
public double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
final long del=(long)1e9+7;
int d, n;
List<List<Integer>> edges;
int[] vals;
long result=0;
boolean[] isUsed;
long goDFS(int curVert, int ans, int minVal, int maxVal){
if (vals[curVert]<minVal)
return 1;
if (vals[curVert]>maxVal)
return 1;
if (vals[curVert]==minVal && isUsed[curVert])
return 1;
long result=1;
for (Integer next : edges.get(curVert)){
if (next!=ans){
result=(result*goDFS(next, curVert, minVal, maxVal))%del;
}
}
result++;
return result;
}
public void Run() throws NumberFormatException, IOException {
//br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter("output.txt");
br=new BufferedReader(new InputStreamReader(System.in)); pw=new PrintWriter(new OutputStreamWriter(System.out));
d=nextInt();
n=nextInt();
edges=new ArrayList<List<Integer>>();
vals=new int[n];
isUsed=new boolean[n];
for (int i=0; i<n; i++){
edges.add(new ArrayList<Integer>());
vals[i]=nextInt();
}
for (int i=0; i<n-1; i++){
int zn1=nextInt()-1;
int zn2=nextInt()-1;
edges.get(zn1).add(zn2);
edges.get(zn2).add(zn1);
}
for (int i=0; i<n; i++){
result+=(goDFS(i,-1,vals[i],vals[i]+d)-1);
result%=del;
isUsed[i]=true;
}
pw.println(result);
pw.flush();
pw.close();
}
} | Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | 4492c0b14a290bf9eeb31e022d1be880 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.util.*;
import java.lang.*;
import java.lang.Math.*;
import java.io.*;
public class cf_276_A {
public static boolean[] f = new boolean[2020];
public static long MOD = 1000000007;
public static int n,d;
public static int[] a = new int[2020];
public static int[][] b = new int[2020][2020];
public static long res = 0;
public static int[] c = new int[2020];
public static int delta;
public static long dfs(int p, int v)
{
if (c[v]>delta + d || ((c[v] == delta + d) && (f[v] == true)) || c[v]<delta)
return 0;
long ans = 1;
for (int i = 1; i <=a[v]; i++)
{
int u = b[v][i];
if (u!=p)
ans = ans*( (dfs(v,u) + 1)% MOD);
ans = ans % MOD;
}
return ans;
}
public static void main(String[] args) throws java.lang.Exception
{
Scanner reader = new Scanner(System.in);
d = reader.nextInt();
n = reader.nextInt();
int u,v;
for (int i=1; i<=n; i++) c[i] = reader.nextInt();
for (int i=1; i<n; i++)
{
u = reader.nextInt();
v = reader.nextInt();
a[u]++;
a[v]++;
b[u][a[u]] = v;
b[v][a[v]] = u;
}
for (int i=1; i<=n; i++)
{
delta = c[i] - d;
res = (res + dfs(i,i)) % MOD;
f[i] = true;
}
System.out.print(res);
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | c5812f95bfec269510e7fb2025f1b852 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
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.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* 4 4
* 1 5 3 4
* 1 2
* 1 3
* 2 3
* 3 3
*
*
* @author pttrung
*/
public class A {
public static long Mod = (long) (1e9) + 7;
static long[] dp;
static int[] X = {0, -1, 0, 1};
static int[] Y = {-1, 0, 1, 0};
public static void main(String[] args) throws FileNotFoundException {
PrintWriter out = new PrintWriter(System.out);
//PrintWriter out = new PrintWriter(new FileOutputStream(new File("output.txt")));
Scanner in = new Scanner();
int d = in.nextInt();
int n = in.nextInt();
Entry[] data = new Entry[n];
int[] val = new int[n];
ArrayList<Integer>[] map = new ArrayList[n];
for (int i = 0; i < n; i++) {
data[i] = new Entry(i, in.nextInt());
val[i] = data[i].value;
map[i] = new ArrayList();
}
Arrays.sort(data);
for (int i = 0; i < n - 1; i++) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
map[u].add(v);
map[v].add(u);
}
boolean[] check = new boolean[n];
long result = 0;
for (Entry e : data) {
long v = cal(e.index, e.index, e.index, d, map, check, val);
// out.println(v + " " + e.index);
result += v;
result %= Mod;
check[e.index] = true;
}
out.println(result);
out.close();
}
static long cal(int index, int origin, int pa, int d, ArrayList<Integer>[] map, boolean[] check, int[] val) {
if (check[index]) {
return 0;
}
if (val[origin] - val[index] > d) {
return 0;
}
long result = 1;
for (int i : map[index]) {
if (i != pa) {
result *= (cal(i, origin, index, d, map, check, val) + 1);
result %= Mod;
}
}
return result;
}
static class Entry implements Comparable<Entry> {
int index, value;
Entry(int index, int value) {
this.index = index;
this.value = value;
}
@Override
public int compareTo(Entry o) {
return o.value - value;
}
}
static int[] KMP(String v) {
int i = 0, j = -1;
int[] result = new int[v.length() + 1];
result[0] = -1;
while (i < v.length()) {
while (j >= 0 && v.charAt(i) != v.charAt(j)) {
j = result[j];
}
i++;
j++;
result[i] = j;
}
return result;
}
static int find(int index, int[] u) {
if (index != u[index]) {
return u[index] = find(u[index], u);
}
return index;
}
public static long pow(int a, int b, long mod) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long v = pow(a, b / 2, mod);
if (b % 2 == 0) {
return (v * v) % mod;
} else {
return (((v * v) % mod) * a) % mod;
}
}
public static int[][] powSquareMatrix(int[][] A, long p) {
int[][] unit = new int[A.length][A.length];
for (int i = 0; i < unit.length; i++) {
unit[i][i] = 1;
}
if (p == 0) {
return unit;
}
int[][] val = powSquareMatrix(A, p / 2);
if (p % 2 == 0) {
return mulMatrix(val, val);
} else {
return mulMatrix(A, mulMatrix(val, val));
}
}
public static int[][] mulMatrix(int[][] A, int[][] B) {
int[][] result = new int[A.length][B[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
long temp = 0;
for (int k = 0; k < A[0].length; k++) {
temp += ((long) A[i][k] * B[k][j] % Mod);
temp %= Mod;
}
temp %= Mod;
result[i][j] = (int) temp;
}
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
static class FT {
int[] data;
FT(int n) {
data = new int[n];
}
void update(int index, int val) {
// System.out.println("UPDATE INDEX " + index);
while (index < data.length) {
data[index] += val;
index += index & (-index);
// System.out.println("NEXT " +index);
}
}
int get(int index) {
// System.out.println("GET INDEX " + index);
int result = 0;
while (index > 0) {
result += data[index];
index -= index & (-index);
// System.out.println("BACK " + index);
}
return result;
}
}
static long gcd(long a, long b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
static long pow(long a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val % Mod;
} else {
return (val * val % Mod) * a % Mod;
}
}
// static Point intersect(Point a, Point b, Point c) {
// double D = cross(a, b);
// if (D != 0) {
// return new Point(cross(c, b) / D, cross(a, c) / D);
// }
// return null;
// }
//
// static Point convert(Point a, double angle) {
// double x = a.x * cos(angle) - a.y * sin(angle);
// double y = a.x * sin(angle) + a.y * cos(angle);
// return new Point(x, y);
// }
static Point minus(Point a, Point b) {
return new Point(a.x - b.x, a.y - b.y);
}
//
// static Point add(Point a, Point b) {
// return new Point(a.x + b.x, a.y + b.y);
// }
//
/**
* Cross product ab*ac
*
* @param a
* @param b
* @param c
* @return
*/
static double cross(Point a, Point b, Point c) {
Point ab = new Point(b.x - a.x, b.y - a.y);
Point ac = new Point(c.x - a.x, c.y - a.y);
return cross(ab, ac);
}
static double cross(Point a, Point b) {
return a.x * b.y - a.y * b.x;
}
/**
* Dot product ab*ac;
*
* @param a
* @param b
* @param c
* @return
*/
static long dot(Point a, Point b, Point c) {
Point ab = new Point(b.x - a.x, b.y - a.y);
Point ac = new Point(c.x - a.x, c.y - a.y);
return dot(ab, ac);
}
static long dot(Point a, Point b) {
long total = a.x * b.x;
total += a.y * b.y;
return total;
}
static double dist(Point a, Point b) {
long total = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
return Math.sqrt(total);
}
static long norm(Point a) {
long result = a.x * a.x;
result += a.y * a.y;
return result;
}
static double dist(Point a, Point b, Point x, boolean isSegment) {
double dist = cross(a, b, x) / dist(a, b);
// System.out.println("DIST " + dist);
if (isSegment) {
Point ab = new Point(b.x - a.x, b.y - a.y);
long dot1 = dot(a, b, x);
long norm = norm(ab);
double u = (double) dot1 / norm;
if (u < 0) {
return dist(a, x);
}
if (u > 1) {
return dist(b, x);
}
}
return Math.abs(dist);
}
static long squareDist(Point a, Point b) {
long x = a.x - b.x;
long y = a.y - b.y;
return x * x + y * y;
}
static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point{" + "x=" + x + ", y=" + y + '}';
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
//System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new FileReader(new File("input.txt")));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | c69426d48daddc932b4892d7b5e9a3bc | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | //package codeforces;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class D {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(System.out);
StringTokenizer stringTokenizer;
String next() throws IOException {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(reader.readLine());
}
return stringTokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
final int MOD = 1000 * 1000 * 1000 + 7;
int sum(int a, int b) {
a += b;
return a >= MOD ? a - MOD : a;
}
@SuppressWarnings("unchecked")
void solve() throws IOException {
final int d = nextInt();
final int n = nextInt();
final int[] a = new int[n + 1];
class Vertex {
int id, a;
Vertex(int id, int a) {
this.id = id;
this.a = a;
}
}
final Vertex[] vertices = new Vertex[n];
for(int i = 0; i < n; i++) {
final int x = nextInt();
vertices[i] = new Vertex(i + 1, x);
a[i + 1] = x;
}
Arrays.sort(vertices, new Comparator<Vertex>() {
@Override
public int compare(Vertex o1, Vertex o2) {
return o1.a - o2.a;
}
});
final List<List<Integer>> g = new ArrayList<>();
for(int i = 0; i <= n; i++) {
g.add(new ArrayList<Integer>());
}
for(int i = 1; i < n; i++) {
int u = nextInt();
int v = nextInt();
g.get(u).add(v);
g.get(v).add(u);
}
final boolean[] used = new boolean[n + 1];
class Utils {
final int MOD = 1000 * 1000 * 1000 + 7;
int sum(int a, int b) {
a += b;
return a >= MOD ? a - MOD : a;
}
int product(int a, int b) {
return (int)(1l * a * b % MOD);
}
int countTrees(int u, int parent, int root) {
int result = 1;
for (int v : g.get(u)) {
if(!used[v] && a[v] >= a[root] && a[v] <= a[root] + d && v != parent) {
result = product(result, 1 + countTrees(v, u, root));
}
}
return result;
}
}
Utils utils = new Utils();
int ans = 0;
for(int i = 0; i < n; i++) {
final int id = vertices[i].id;
ans = utils.sum(ans, utils.countTrees(id, 0, id));
used[id] = true;
}
writer.println(ans);
writer.close();
}
public static void main(String[] args) throws IOException {
new D().solve();
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | a6fc80d83203641d247cb39bb267aaf3 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedInputStream;
import java.util.Scanner;
/**
* Created by liverliu on 14/11/17.
*/
public class Main {
static class Node {
int val;
}
static class Edge {
public int u, v, next;
}
static Node node[] = new Node[2005];
static Edge edge[] = new Edge[4010];
static int head[] = new int[2005], E;
static void addEdge(int u, int v) {
edge[E].u = u;
edge[E].v = v;
edge[E].next = head[u];
head[u] = E++;
}
static final int mod = 1000000007;
static int d,n;
static void init() {
E = 0;
for(int i=0;i<n;i++) {
head[i] = -1;
node[i] = new Node();
edge[i*2] = new Edge();
edge[i*2+1] = new Edge();
}
}
static long dfs(int u, int fa, int rt) {
long ans = 1;
for(int i=head[u]; i!=-1; i=edge[i].next) {
int v = edge[i].v;
if(fa == v || node[v].val > node[rt].val || (node[v].val == node[rt].val && v > rt) ||
node[rt].val-node[v].val > d) {
continue;
}
long tmp = dfs(v, u, rt);
ans = (ans * (tmp + 1)) %mod;
}
return ans;
}
public static void main(String args[]) {
Scanner scan = new Scanner(new BufferedInputStream(System.in));
while(scan.hasNext()) {
d = scan.nextInt();
n = scan.nextInt();
init();
for(int i=0;i<n;i++) {
node[i].val = scan.nextInt();
}
for(int i=0;i<n-1;i++) {
int u = scan.nextInt();
int v = scan.nextInt();
addEdge(--u, --v);
addEdge(v, u);
}
long ans=0;
for(int i=0;i<n;i++) {
ans += dfs(i, -1, i);
ans %= mod;
}
System.out.println(ans);
}
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | 2a5a62be9a4b6efa988eb61f4f868676 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.BigInteger;
public class Main{
final boolean isFileIO = false;
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
String delim = " ";
public static void main(String[] args) throws IOException {
Main m = new Main();
m.initIO();
m.solve();
m.in.close();
m.out.close();
}
public void initIO() throws IOException {
if(!isFileIO) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("maxnumber.in"));
out = new PrintWriter("maxnumber.out");
}
}
String nextToken() throws IOException {
if(!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken(delim);
}
String readLine() throws IOException {
return in.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
class Node implements Comparable<Node> {
public int u, h;
public Node(int u, int h) {
this.u = u;
this.h = h;
}
public int compareTo(Node y) {
if(this.h < y.h) {
return - 1;
}
if(this.h > y.h) {
return 1;
}
return 0;
}
}
ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>();
boolean[] visited;
int[] dp;
boolean[] used;
int[] a;
int d;
int cur;
int mod = 1_000_000_007;
public void solve() throws IOException {
int n;
d = nextInt(); n = nextInt();
a = new int[n];
dp = new int[n];
visited = new boolean[n];
used = new boolean[n];
for(int i = 0; i < n; i++) {
a[i] = nextInt();
}
for(int i = 0; i < n; i++) {
g.add(new ArrayList<Integer>());
}
for(int i = 0; i < n - 1; i++) {
int u = nextInt() - 1;
int v = nextInt() - 1;
g.get(u).add(v);
g.get(v).add(u);
}
long ans = 0;
for(int i = 0; i < n; i++) {
Arrays.fill(visited, false);
Arrays.fill(dp, 0);
cur = i;
dfs(i);
used[i] = true;
ans = (ans + dp[i]) % mod;
}
out.println(ans);
}
public void dfs(int u) {
visited[u] = true;
for(int i = 0; i < g.get(u).size(); i++) {
if(!visited[g.get(u).get(i)]) {
dfs(g.get(u).get(i));
}
}
if(a[u] == a[cur] && used[u]) {
dp[u] = 0;
return;
}
if(a[u] >= a[cur] && a[u] <= a[cur] + d) {
dp[u] = 1;
for(int i = 0; i < g.get(u).size(); i++) {
dp[u] = (int)Utils.mulmod(dp[u], dp[g.get(u).get(i)] + 1, mod);
}
}
}
}
class Utils {
public static long binpow(long a, long exp, long mod) {
if(exp == 0) {
return 1;
}
if(exp % 2 == 0) {
long temp = binpow(a, exp / 2, mod);
return (temp * temp) % mod;
} else {
return (binpow(a, exp - 1, mod) * a) % mod;
}
}
public static long inv(long a, long mod) {
return binpow(a, mod - 2, mod);
}
public static long addmod(long a, long b, long mod) {
return (a + b + 2 * mod) % mod;
}
public static long gcd(long a, long b) {
if(b == 0)
return a;
return gcd(b, a % b);
}
//mul must be < 10^18
public static long mulmod(long a, long b, long mod) {
return (a * b + (((a * b) / mod) + 1) * mod) % mod;
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | ee454d706bb15d339c0292db4cdf4e4d | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | //package round277;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class D {
InputStream is;
PrintWriter out;
String INPUT = "";
int mod = 1000000007;
void solve()
{
int d = ni(), n = ni();
int[] a = na(n);
int[] from = new int[n-1];
int[] to = new int[n-1];
for(int i = 0;i < n-1;i++){
from[i] = ni()-1;
to[i] = ni()-1;
}
int[][] g = packU(n, from, to);
long ret = 0;
for(int i = 0;i < n;i++){
ret += dfs(i, -1, i, g, d, a);
}
out.println(ret%mod);
}
long dfs(int cur, int par, int root, int[][] g, int d, int[] a)
{
long ret = 1;
for(int e : g[cur]){
if(e != par && (a[e] < a[root] || a[e] == a[root] && e < root) && a[e] >= a[root]-d){
ret = ret * (dfs(e, cur, root, g, d, a)+1) % mod;
}
}
return ret;
}
static int[][] packU(int n, int[] from, int[] to) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int f : from)
p[f]++;
for (int t : to)
p[t]++;
for (int i = 0; i < n; i++)
g[i] = new int[p[i]];
for (int i = 0; i < from.length; i++) {
g[from[i]][--p[from[i]]] = to[i];
g[to[i]][--p[to[i]]] = from[i];
}
return g;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new D().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | d20edcb417f3f7215876f62dfa5a2b6d | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.util.*;
public class validsets {
private static Reader in;
private static PrintWriter out;
public static int D, N;
public static int[] val;
public static int[] eadj, eprev, elast;
public static int eidx;
public static int mod = 1000000007;
public static void addEdge(int a, int b) {
eadj[eidx] = b; eprev[eidx] = elast[a]; elast[a] = eidx++;
eadj[eidx] = a; eprev[eidx] = elast[b]; elast[b] = eidx++;
}
public static void main(String[] args) throws IOException {
in = new Reader();
out = new PrintWriter(System.out, true);
D = in.nextInt();
N = in.nextInt();
val = new int[N];
for (int i = 0; i < N; i++) {
val[i] = in.nextInt();
}
eadj = new int[2 * N];
eprev = new int[2 * N];
elast = new int[N];
eidx = 0;
Arrays.fill(elast, -1);
for (int i = 0; i < N-1; i++) {
addEdge(in.nextInt() - 1, in.nextInt() - 1);
}
long total = 0;
for (int i = 0; i < N; i++) {
total = (total + solve(i)) % mod;
}
out.println(total);
out.close();
System.exit(0);
}
public static int V, R;
public static long solve (int root) {
V = val[root];
R = root;
return dfs(root, -1);
}
public static long dfs(int node, int par) {
long res = 1;
for (int e = elast[node]; e != -1; e = eprev[e]) {
if (eadj[e] == par) continue;
if ((V == val[eadj[e]] && eadj[e] < R) || (val[eadj[e]] < V && V - val[eadj[e]] <= D)) {
res = (res * (1 + dfs(eadj[e], node))) % mod;
}
}
return res;
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[1 << 20];
int cnt = 0;
byte c = read();
while (c <= ' ')
c = read();
do {
buf[cnt++] = c;
} while ((c = read()) != '\n');
return new String(buf, 0, cnt);
}
public String next() throws IOException {
byte[] buf = new byte[1 << 20];
int cnt = 0;
byte c = read();
while (c <= ' ')
c = read();
do {
buf[cnt++] = c;
} while ((c = read()) > ' ');
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | 6153bb89656ba8ebd4aacf0c3f3a6fc0 | train_000.jsonl | 1415718000 | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7). | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static final int MAX_RESULT = 1000000007;
private static int maxDiff = 0;
private static class Node{
public int index;
public int value;
public ArrayList<Node> neighbors;
public Node(int index, int value){
this.index = index;
this.value = value;
this.neighbors = new ArrayList<Node>();
}
}
private static long nValidSubsets(Node root, Node currNode, Node currParent){
if (currNode.value < root.value){
return 0;
} else if (currNode.value == root.value && currNode.index < root.index){
// to avoid double counting; stop traversing tree if node has:
// 1. same value as root, 2. smaller index than root
return 0;
} else if (currNode.value - root.value > maxDiff){
return 0;
} else {
long nValidSubsets = 1;
ArrayList<Node> neighbors = currNode.neighbors;
for (Node neighbor: neighbors){
if (neighbor != currParent){
long temp = nValidSubsets * (nValidSubsets(root, neighbor, currNode) + 1);
nValidSubsets = temp % MAX_RESULT;
}
}
return nValidSubsets;
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
maxDiff = in.nextInt();
int nNodes = in.nextInt();
// get all the nodes
Node[] allNodes = new Node[nNodes];
for (int i = 0; i < nNodes; i++){
allNodes[i] = new Node(i, in.nextInt());
}
// add all connections
for (int i = 0; i < nNodes - 1; i++){
Node node1 = allNodes[in.nextInt() - 1];
Node node2 = allNodes[in.nextInt() - 1];
node1.neighbors.add(node2);
node2.neighbors.add(node1);
}
long result = 0;
for (Node node: allNodes){
result = ((result + nValidSubsets(node, node, null)) % MAX_RESULT);
}
System.out.println(result);
in.close();
}
}
| Java | ["1 4\n2 1 3 2\n1 2\n1 3\n3 4", "0 3\n1 2 3\n1 2\n2 3", "4 8\n7 8 7 5 4 6 4 10\n1 6\n1 2\n5 8\n1 3\n3 5\n6 7\n3 4"] | 1 second | ["8", "3", "41"] | NoteIn the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | Java 7 | standard input | [
"dp",
"dfs and similar",
"trees",
"math"
] | 88bb9b993ba8aacd6a7cf137415ef7dd | The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000). The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000). Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree. | 2,100 | Print the number of valid sets modulo 1000000007. | standard output | |
PASSED | 742f722d947cfeb9f99d357af4646166 | train_000.jsonl | 1560677700 | Dima worked all day and wrote down on a long paper strip his favorite number $$$n$$$ consisting of $$$l$$$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. | 512 megabytes | import java.io.*;
import java.util.*;
import java.math.BigInteger;
public class Main{
static int mod = (int)(Math.pow(10, 9) + 7);
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt();
String s = sc.next();
int bestInd1 = -1;
int bestInd2= -1;
int minLenDiff = 0;
List<Split> l = new ArrayList<Split>();
for (int i = 1; i < n; i++){
if (s.charAt(i) != '0'){
l.add(new Split(i, Integer.max(n-i, i)));
//out.println(i + " " + l.get(l.size()-1).len);
}
}
Collections.sort(l);
int minLen = l.get(0).len;
List<BigInteger> sol = new ArrayList<BigInteger>();
for (Split spl: l){
if (spl.len != minLen) break;
BigInteger start = new BigInteger(s.substring(0, spl.index));
BigInteger end = new BigInteger(s.substring(spl.index, n));
BigInteger res = start.add(end);
sol.add(res);
}
Collections.sort(sol);
out.println(sol.get(0));
out.close();
}
static class Split implements Comparable<Split>{
int index, len;
public Split(int i, int l){
index =i ;
len = l;
}
public int compareTo(Split o){
return len - o.len;
}
}
static long pow(long a, long N) {
if (N == 0) return 1;
else if (N == 1) return a;
else {
long R = pow(a,N/2);
if (N % 2 == 0) {
return R*R;
}
else {
return R*R*a;
}
}
}
static long powMod(long a, long N) {
if (N == 0) return 1;
else if (N == 1) return a % mod;
else {
long R = powMod(a,N/2) % mod;
R *= R % mod;
if (N % 2 == 1) {
R *= a % mod;
}
return R % mod;
}
}
static void mergeSort(int[] A){ // low to hi sort, single array only
int n = A.length;
if (n < 2) return;
int[] l = new int[n/2];
int[] r = new int[n - n/2];
for (int i = 0; i < n/2; i++){
l[i] = A[i];
}
for (int j = n/2; j < n; j++){
r[j-n/2] = A[j];
}
mergeSort(l);
mergeSort(r);
merge(l, r, A);
}
static void merge(int[] l, int[] r, int[] a){
int i = 0, j = 0, k = 0;
while (i < l.length && j < r.length && k < a.length){
if (l[i] < r[j]){
a[k] = l[i];
i++;
}
else{
a[k] = r[j];
j++;
}
k++;
}
while (i < l.length){
a[k] = l[i];
i++;
k++;
}
while (j < r.length){
a[k] = r[j];
j++;
k++;
}
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
}
| Java | ["7\n1234567", "3\n101"] | 2 seconds | ["1801", "11"] | NoteIn the first example Dima can split the number $$$1234567$$$ into integers $$$1234$$$ and $$$567$$$. Their sum is $$$1801$$$.In the second example Dima can split the number $$$101$$$ into integers $$$10$$$ and $$$1$$$. Their sum is $$$11$$$. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. | Java 11 | standard input | [
"implementation",
"greedy",
"strings"
] | 08bce37778b7bfe478340d5c222ae362 | The first line contains a single integer $$$l$$$ ($$$2 \le l \le 100\,000$$$) — the length of the Dima's favorite number. The second line contains the positive integer $$$n$$$ initially written on the strip: the Dima's favorite number. The integer $$$n$$$ consists of exactly $$$l$$$ digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. | 1,500 | Print a single integer — the smallest number Dima can obtain. | standard output | |
PASSED | a7296fb262f538772ae654ccd4ac06eb | train_000.jsonl | 1560677700 | Dima worked all day and wrote down on a long paper strip his favorite number $$$n$$$ consisting of $$$l$$$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. | 512 megabytes | import java.math.BigInteger;
import java.util.Stack;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
BigInteger one = new BigInteger("0");
Scanner input = new Scanner(System.in);
int len = input.nextInt();
String s = input.next();
BigInteger x,y,ans;
int len1 = (len-1)/2;
int len2 = (len+1)/2;
while(len1 != len && s.charAt(len1) == '0')len1++;
while(s.charAt(len2) == '0')len2--;
if(len2 == 0)
x = one;
else
x = new BigInteger(s.substring(0,len2));
y = new BigInteger(s.substring(len2 , len));
ans = x.add(y);
if(len1 == len)
y = one;
else
y = new BigInteger(s.substring(len1,len));
if(len1 == 0)
len1++;
x = new BigInteger(s.substring(0,len1));
ans = ans.min(x.add(y));
System.out.print(ans);
}
} | Java | ["7\n1234567", "3\n101"] | 2 seconds | ["1801", "11"] | NoteIn the first example Dima can split the number $$$1234567$$$ into integers $$$1234$$$ and $$$567$$$. Their sum is $$$1801$$$.In the second example Dima can split the number $$$101$$$ into integers $$$10$$$ and $$$1$$$. Their sum is $$$11$$$. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. | Java 11 | standard input | [
"implementation",
"greedy",
"strings"
] | 08bce37778b7bfe478340d5c222ae362 | The first line contains a single integer $$$l$$$ ($$$2 \le l \le 100\,000$$$) — the length of the Dima's favorite number. The second line contains the positive integer $$$n$$$ initially written on the strip: the Dima's favorite number. The integer $$$n$$$ consists of exactly $$$l$$$ digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. | 1,500 | Print a single integer — the smallest number Dima can obtain. | standard output | |
PASSED | 7041a69ac89afcf87fd2373f6734d77f | train_000.jsonl | 1560677700 | Dima worked all day and wrote down on a long paper strip his favorite number $$$n$$$ consisting of $$$l$$$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. | 512 megabytes | // practice with kaiboy
import java.io.*;
import java.util.*;
public class CF1181B extends PrintWriter {
CF1181B() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1181B o = new CF1181B(); o.main(); o.flush();
}
int split(byte[] cc, int l, int n, int[] aa) {
int r = n - l, m = Math.max(l, r);
for (int h = 0; h < m; h++) {
int a = 0;
if (h < l)
a += cc[l - 1 - h] - '0';
if (h < r)
a += cc[n - 1 - h] - '0';
aa[h] = a;
}
for (int h = 0; h < m; h++) {
aa[h + 1] += aa[h] / 10;
aa[h] %= 10;
}
if (aa[m] > 0)
m++;
return m;
}
int compare(int[] aa, int na, int[] bb, int nb) {
if (na != nb)
return na - nb;
for (int i = na - 1; i >= 0; i--)
if (aa[i] != bb[i])
return aa[i] - bb[i];
return 0;
}
void print_(int[] aa, int n) {
while (n-- > 0)
print(aa[n]);
println();
}
void main() {
int n = sc.nextInt();
byte[] cc = sc.next().getBytes();
int i, j;
if (n % 2 == 0)
i = j = n / 2;
else {
i = n / 2;
j = i + 1;
}
while (cc[i] == '0')
i--;
while (j < n && cc[j] == '0')
j++;
int[] aa = null, bb = null; int na = n + 1, nb = n + 1;
if (i > 0)
na = split(cc, i, n, aa = new int[n]);
if (j < n)
nb = split(cc, j, n, bb = new int[n]);
if (na < nb || na == nb && compare(aa, na, bb, nb) <= 0)
print_(aa, na);
else
print_(bb, nb);
}
}
| Java | ["7\n1234567", "3\n101"] | 2 seconds | ["1801", "11"] | NoteIn the first example Dima can split the number $$$1234567$$$ into integers $$$1234$$$ and $$$567$$$. Their sum is $$$1801$$$.In the second example Dima can split the number $$$101$$$ into integers $$$10$$$ and $$$1$$$. Their sum is $$$11$$$. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. | Java 11 | standard input | [
"implementation",
"greedy",
"strings"
] | 08bce37778b7bfe478340d5c222ae362 | The first line contains a single integer $$$l$$$ ($$$2 \le l \le 100\,000$$$) — the length of the Dima's favorite number. The second line contains the positive integer $$$n$$$ initially written on the strip: the Dima's favorite number. The integer $$$n$$$ consists of exactly $$$l$$$ digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. | 1,500 | Print a single integer — the smallest number Dima can obtain. | standard output | |
PASSED | 9062d43529a947639982a7e2cb306735 | train_000.jsonl | 1560677700 | Dima worked all day and wrote down on a long paper strip his favorite number $$$n$$$ consisting of $$$l$$$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. | 512 megabytes |
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int len;
len = input.nextInt();
String ss = input.nextLine();
ss = input.nextLine();
BigInteger a = new BigInteger(ss);
BigInteger b = BigInteger.ONE, ans = a;
int i, j;
if(len % 2 > 0){
i = len / 2;
j = i + 1;
} else {
j = len / 2;
i = j - 1;
}
while(i >= 0 && ss.charAt(i) == '0') i --;
while(j < len && ss.charAt(j) == '0') j ++;
BigInteger x1 = new BigInteger (ss.substring(i));
BigInteger x2;
if(i > 0)
x2 = new BigInteger(ss.substring(0, i));
else
x2 = new BigInteger(ss);
BigInteger y1;
if(j < len)
y1 = new BigInteger (ss.substring(j));
else y1 = new BigInteger(ss);
BigInteger y2 = new BigInteger (ss.substring(0, j));
System.out.println((x1.add(x2)).min(y1.add(y2)));
}
}
| Java | ["7\n1234567", "3\n101"] | 2 seconds | ["1801", "11"] | NoteIn the first example Dima can split the number $$$1234567$$$ into integers $$$1234$$$ and $$$567$$$. Their sum is $$$1801$$$.In the second example Dima can split the number $$$101$$$ into integers $$$10$$$ and $$$1$$$. Their sum is $$$11$$$. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. | Java 11 | standard input | [
"implementation",
"greedy",
"strings"
] | 08bce37778b7bfe478340d5c222ae362 | The first line contains a single integer $$$l$$$ ($$$2 \le l \le 100\,000$$$) — the length of the Dima's favorite number. The second line contains the positive integer $$$n$$$ initially written on the strip: the Dima's favorite number. The integer $$$n$$$ consists of exactly $$$l$$$ digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. | 1,500 | Print a single integer — the smallest number Dima can obtain. | standard output | |
PASSED | e8c07919aa4114870523a335237cd971 | train_000.jsonl | 1560677700 | Dima worked all day and wrote down on a long paper strip his favorite number $$$n$$$ consisting of $$$l$$$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. | 512 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
InputReader input = new InputReader(System.in);
int len;
len = input.nextInt();
String ss = input.next();
//ss = input.nextLine();
BigInteger a = new BigInteger(ss);
int i, j;
if(len % 2 > 0){
i = len / 2;
j = i + 1;
} else {
j = len / 2;
i = j - 1;
}
while(i >= 0 && ss.charAt(i) == '0') i --;
while(j < len && ss.charAt(j) == '0') j ++;
BigInteger x1 = new BigInteger (ss.substring(i));
BigInteger x2;
if(i > 0)
x2 = new BigInteger(ss.substring(0, i));
else
x2 = new BigInteger(ss);
BigInteger y1;
if(j < len)
y1 = new BigInteger (ss.substring(j));
else y1 = new BigInteger(ss);
BigInteger y2 = new BigInteger (ss.substring(0, j));
System.out.println((x1.add(x2)).min(y1.add(y2)));
}
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 | ["7\n1234567", "3\n101"] | 2 seconds | ["1801", "11"] | NoteIn the first example Dima can split the number $$$1234567$$$ into integers $$$1234$$$ and $$$567$$$. Their sum is $$$1801$$$.In the second example Dima can split the number $$$101$$$ into integers $$$10$$$ and $$$1$$$. Their sum is $$$11$$$. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. | Java 11 | standard input | [
"implementation",
"greedy",
"strings"
] | 08bce37778b7bfe478340d5c222ae362 | The first line contains a single integer $$$l$$$ ($$$2 \le l \le 100\,000$$$) — the length of the Dima's favorite number. The second line contains the positive integer $$$n$$$ initially written on the strip: the Dima's favorite number. The integer $$$n$$$ consists of exactly $$$l$$$ digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. | 1,500 | Print a single integer — the smallest number Dima can obtain. | standard output | |
PASSED | 258fcca1fd73ec4674b7c545abb886b1 | train_000.jsonl | 1560677700 | Dima worked all day and wrote down on a long paper strip his favorite number $$$n$$$ consisting of $$$l$$$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. | 512 megabytes |
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Split_the_Number {
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}catch(IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}catch(IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader sc = new FastReader();
int n = sc.nextInt();
String s = sc.nextLine();
int mid = (n / 2);
if(s.charAt(mid) == '0') {
int l = mid;
int r = mid;
while(s.charAt(l) == '0') {
l--;
}
while(r < n && s.charAt(r) == '0') {
r++;
}
BigInteger num1 = new BigInteger(s);
if(l != 0) {
num1 = new BigInteger(s.substring(0, l)).add(new BigInteger(s.substring(l)));
}
if(r != n) {
BigInteger num2 = new BigInteger(s.substring(0, r)).add(new BigInteger(s.substring(r)));
if(num2.compareTo(num1) < 0) {
num1 = num2;
}
}
System.out.println(num1);
}else{
if(n % 2 == 0) {
BigInteger num1 = new BigInteger(s.substring(0 , mid)).add(new BigInteger(s.substring(mid)));
System.out.println(num1);
}else {
BigInteger num1 = new BigInteger(s.substring(0 , mid)).add(new BigInteger(s.substring(mid)));
BigInteger num2 = new BigInteger(s.substring(0 , mid + 1)).add(new BigInteger(s.substring(mid + 1)));
if(num2.compareTo(num1) < 0) {
num1 = num2;
}
System.out.println(num1);
}
}
}
}
| Java | ["7\n1234567", "3\n101"] | 2 seconds | ["1801", "11"] | NoteIn the first example Dima can split the number $$$1234567$$$ into integers $$$1234$$$ and $$$567$$$. Their sum is $$$1801$$$.In the second example Dima can split the number $$$101$$$ into integers $$$10$$$ and $$$1$$$. Their sum is $$$11$$$. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. | Java 11 | standard input | [
"implementation",
"greedy",
"strings"
] | 08bce37778b7bfe478340d5c222ae362 | The first line contains a single integer $$$l$$$ ($$$2 \le l \le 100\,000$$$) — the length of the Dima's favorite number. The second line contains the positive integer $$$n$$$ initially written on the strip: the Dima's favorite number. The integer $$$n$$$ consists of exactly $$$l$$$ digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. | 1,500 | Print a single integer — the smallest number Dima can obtain. | standard output | |
PASSED | 0fac4b8221e037d77db50a75e31e87f6 | train_000.jsonl | 1560677700 | Dima worked all day and wrote down on a long paper strip his favorite number $$$n$$$ consisting of $$$l$$$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. | 512 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class pro{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int l = input.nextInt();
String n = input.next();
BigInteger x = null, y = null, z = null;
boolean f = false, ff = false, fa = false;
if(n.charAt(l / 2) != '0'){
int cut = l / 2;
BigInteger first = new BigInteger(n.substring(0, cut));
BigInteger second = new BigInteger(n.substring(cut));
x = first.add(second);
f = true;
}
for(int i = l / 2 + 1; i < l; i++){
if(n.charAt(i) != '0'){
BigInteger first = new BigInteger(n.substring(0, i));
BigInteger second = new BigInteger(n.substring(i));
y = first.add(second);
ff = true;
break;
}
}
for(int i = l / 2 - 1; i > 0; i--){
if(n.charAt(i) != '0'){
BigInteger first = new BigInteger(n.substring(0, i));
BigInteger second = new BigInteger(n.substring(i));
z = first.add(second);
fa = true;
break;
}
}
BigInteger ans = null;
if(f)ans = x;
else if(ff)ans = y;
else if(fa)ans = z;
if(f)ans = ans.min(x);
if(ff)ans = ans.min(y);
if(fa)ans = ans.min(z);
System.out.println(ans);
input.close();
}
} | Java | ["7\n1234567", "3\n101"] | 2 seconds | ["1801", "11"] | NoteIn the first example Dima can split the number $$$1234567$$$ into integers $$$1234$$$ and $$$567$$$. Their sum is $$$1801$$$.In the second example Dima can split the number $$$101$$$ into integers $$$10$$$ and $$$1$$$. Their sum is $$$11$$$. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. | Java 11 | standard input | [
"implementation",
"greedy",
"strings"
] | 08bce37778b7bfe478340d5c222ae362 | The first line contains a single integer $$$l$$$ ($$$2 \le l \le 100\,000$$$) — the length of the Dima's favorite number. The second line contains the positive integer $$$n$$$ initially written on the strip: the Dima's favorite number. The integer $$$n$$$ consists of exactly $$$l$$$ digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. | 1,500 | Print a single integer — the smallest number Dima can obtain. | standard output | |
PASSED | 40bc1dc260a77b9472b23052ce187d34 | train_000.jsonl | 1560677700 | Dima worked all day and wrote down on a long paper strip his favorite number $$$n$$$ consisting of $$$l$$$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain. | 512 megabytes | // package cp;
import java.io.*;
import java.math.*;
import java.util.*;
public class Cf_one {
public static void main(String[] args) throws IOException {
PrintWriter out = new PrintWriter(System.out);
Readers.init(System.in);
int l=Readers.nextInt();
String s=Readers.next();
int ll=-1;
int rr=-1;
for(int i=(int) Math.ceil((double)s.length()/2)-1;i>=0;i--) {
if(s.charAt(i)!='0') {
ll=i;
break;
}
}
for (int i=(int) Math.ceil((double)s.length()/2);i<=s.length()-1;i++) {
if(s.charAt(i)!='0') {
rr=i;
break;
}
}
// int seg_1;int seg_2;int seg_3;int seg_4;
BigInteger seg_1;BigInteger seg_2;
BigInteger seg_3;BigInteger seg_4;
// System.out.println(ll);
if(rr==-1) {
// seg_1=Integer.parseInt(s.substring(0,ll));
seg_1=new BigInteger(s.substring(0,ll));
seg_2=new BigInteger(s.substring(ll));
// seg_2=Integer.parseInt(s.substring(ll));
System.out.println(seg_1.add(seg_2));
}
else {
String temp=String.valueOf(s.charAt(0));
if(ll!=0)seg_1=new BigInteger(s.substring(0,ll));
else seg_1=new BigInteger(temp);
// else seg_1=s.charAt(0);
// seg_2=Integer.parseInt(s.substring(ll));
seg_2=new BigInteger(s.substring(ll));
// seg_3=Integer.parseInt(s.substring(0,rr));
seg_3=new BigInteger(s.substring(0,rr));
// seg_4=Integer.parseInt(s.substring(rr));
seg_4=new BigInteger(s.substring(rr));
// System.out.println(seg_1+" "+seg_2);
// if(seg_1.add(seg_2)>seg_3.add(seg_4));
System.out.println(seg_1.add(seg_2).min(seg_3.add(seg_4)));
// System.out.println(Math.min(seg_1.add(seg_2),seg_3.add(seg_4)));
}
out.flush();
}
}
class Readers {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException{
return Long.parseLong(next());
}
} | Java | ["7\n1234567", "3\n101"] | 2 seconds | ["1801", "11"] | NoteIn the first example Dima can split the number $$$1234567$$$ into integers $$$1234$$$ and $$$567$$$. Their sum is $$$1801$$$.In the second example Dima can split the number $$$101$$$ into integers $$$10$$$ and $$$1$$$. Their sum is $$$11$$$. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros. | Java 11 | standard input | [
"implementation",
"greedy",
"strings"
] | 08bce37778b7bfe478340d5c222ae362 | The first line contains a single integer $$$l$$$ ($$$2 \le l \le 100\,000$$$) — the length of the Dima's favorite number. The second line contains the positive integer $$$n$$$ initially written on the strip: the Dima's favorite number. The integer $$$n$$$ consists of exactly $$$l$$$ digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip. | 1,500 | Print a single integer — the smallest number Dima can obtain. | standard output | |
PASSED | 2fbf913f8d361bccadd8c8a3eb1bbe70 | train_000.jsonl | 1349623800 | One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution. | 256 megabytes | //package com.company;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Created by uzer on 02.03.2016.
*/
public class Team {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
int tasksNum = 0;
int n = in.nextInt();
for (int i = 0; i < n; i++) {
int p = in.nextInt();
int v = in.nextInt();
int t = in.nextInt();
if (( p==1 && v==1) || ( t==1 && v==1) || ( t==1 && p==1)){
tasksNum++;
}
}
System.out.println(tasksNum);
}
}
| Java | ["3\n1 1 0\n1 1 1\n1 0 0", "2\n1 0 0\n0 1 1"] | 2 seconds | ["2", "1"] | NoteIn the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it. In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution. | Java 7 | standard input | [
"greedy",
"brute force"
] | 3542adc74a41ccfd72008faf983ffab5 | The first input line contains a single integer n (1 ≤ n ≤ 1000) — the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces. | 800 | Print a single integer — the number of problems the friends will implement on the contest. | standard output | |
PASSED | 626fc3f3394c8717ca207b80b253dab2 | train_000.jsonl | 1349623800 | One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution. | 256 megabytes | import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class PlayGround {
public static void main(String[] args) throws Exception {
Eduardo();
}
public static void Eduardo() throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String test = "";
int count = 0;
int total = Integer.parseInt(br.readLine());
while((test = br.readLine()) != null){
int innerCount = 0;
String [] testViews = test.split(" ");
int[] testViewsArray = new int[testViews.length];
for(int i = 0; i<testViews.length; i++){
if (Integer.parseInt(testViews[i]) == 0){
innerCount ++;
if(innerCount>1){
count++;
break;
}
}
}
}
System.out.println(total-count);
}
} | Java | ["3\n1 1 0\n1 1 1\n1 0 0", "2\n1 0 0\n0 1 1"] | 2 seconds | ["2", "1"] | NoteIn the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it. In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution. | Java 7 | standard input | [
"greedy",
"brute force"
] | 3542adc74a41ccfd72008faf983ffab5 | The first input line contains a single integer n (1 ≤ n ≤ 1000) — the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces. | 800 | Print a single integer — the number of problems the friends will implement on the contest. | standard output | |
PASSED | 38c1458ab9fffdd6e29cd3282197da23 | train_000.jsonl | 1349623800 | One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution. | 256 megabytes | import java.util.Scanner;
public class team {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int c = 0;
int d = 0;
for(int i=0;i<n;i++) {
for(int j=0; j< 3 ; j++) {
int a = in.nextInt();
c += a;
a = 0;
}
if(c >= 2) {
d += 1;
}
c = 0;
} System.out.print(d);
}
} | Java | ["3\n1 1 0\n1 1 1\n1 0 0", "2\n1 0 0\n0 1 1"] | 2 seconds | ["2", "1"] | NoteIn the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it. In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution. | Java 7 | standard input | [
"greedy",
"brute force"
] | 3542adc74a41ccfd72008faf983ffab5 | The first input line contains a single integer n (1 ≤ n ≤ 1000) — the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces. | 800 | Print a single integer — the number of problems the friends will implement on the contest. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.