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 listlengths 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 | 36c0715473719ac846fbf89747862dc1 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.AbstractCollection;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.AbstractQueue;
import java.util.Comparator;
import java.util.ArrayList;
/**
* 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;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
T1106D solver = new T1106D();
solver.solve(1, in, out);
out.close();
}
static class T1106D {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt(), m = in.nextInt();
ArrayList<Integer>[] g = new ArrayList[n];
for (int i = 0; i < n; ++i) g[i] = new ArrayList<>();
for (int i = 0; i < m; ++i) {
int to = in.nextInt() - 1, from = in.nextInt() - 1;
g[to].add(from);
g[from].add(to);
}
boolean[] used = new boolean[n];
Comparator<Integer> Comparators = new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
if (a > b)
return 1;
else if (a < b)
return -1;
else
return 0;
}
};
PriorityQueue<Integer> pQueue = new PriorityQueue(Comparators);
pQueue.addAll(g[0]);
out.print(1 + " ");
used[0] = true;
while (!pQueue.isEmpty()) {
int vert = pQueue.poll();
while (!pQueue.isEmpty() && used[vert]) vert = pQueue.poll();
if (pQueue.isEmpty() && used[vert]) break;
out.print(vert + 1 + " ");
pQueue.addAll(g[vert]);
used[vert] = true;
}
}
}
}
| Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 0c5c8e600a66ecc9adb81f888133cec3 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
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 void main(String args[]) throws Exception {
new Thread(null, new Solution(), "Main", 1 << 27).start();
}
public static void addEdge(ArrayList<ArrayList<Integer>> adj,int u,int v)
{
adj.get(u).add(v);
adj.get(v).add(u);
}
public void run() {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n=in.nextInt();
int m=in.nextInt();
ArrayList<ArrayList<Integer>> adj=new ArrayList<ArrayList<Integer>>();
for(int i=1;i<=n+1;i++)
adj.add(new ArrayList<Integer>());
for(int i=0;i<m;i++)
addEdge(adj, in.nextInt(), in.nextInt());
boolean visited[]=new boolean[n+1];
for(int i=1;i<=n;i++)
visited[i]=false;
PriorityQueue<Integer> PQ=new PriorityQueue<Integer>();
PQ.add(1);
visited[1]=true;
while(!PQ.isEmpty())
{
int p=PQ.poll();
w.print(p+" ");
for(int i=0;i<adj.get(p).size();i++)
{
if(!visited[adj.get(p).get(i)])
{
visited[adj.get(p).get(i)]=true;
PQ.add(adj.get(p).get(i));
}
}
}
w.flush();
w.close();
}
} | Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 839ccc3264c6ce118d1fe13fbefeef81 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.util.*;
public class lexigraph {
private static boolean[] marked;
private static int s;
private static int count;
private static String str;
private final int V;
private static ArrayList<Integer> adj[];
private static PriorityQueue<Integer> adjacent ;
public lexigraph (int V)
{
this.V = V;
adjacent= new PriorityQueue<Integer>(V);
str="";
marked=new boolean[V+1];
adj=new ArrayList[V+1];
for (int v = 1; v <= V; v++)
{
adj[v] = new ArrayList<Integer>();
}
}
/*
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i=0;i<n;i++)
adj.add(new ArrayList<Integer>());
for(int i=0;i<m;i++) {
int v1 = scan.nextInt()-1;
int v2 = scan.nextInt()-1;
adj.get(v1).add(v2);
adj.get(v2).add(v1);
}
*/
public static void addEdge(int v,int w)
{
adj[v].add(w);
adj[w].add(v);
}
private static void dfs(lexigraph G, int v)
{
adjacent.add(v);
marked[v]=true;
while(adjacent.peek()!=null)
{
v=adjacent.poll();
System.out.print(v+" ");
for (int w : G.adj[v])
{
if(marked[w]!=true)
{
marked[w] = true;
adjacent.add(w);
}
}
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
lexigraph obj=new lexigraph(n);
int t=sc.nextInt();
for(int i=0;i<t;i++)
{
int a=sc.nextInt();
int b=sc.nextInt();
obj.addEdge(a, b);
}
dfs(obj,1);
}
} | Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | f67dc31c94626a58bcf683d152a7f8c5 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class D {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int n = scanner.nextInt();
int m = scanner.nextInt();
Graph g = new Graph(n);
for (int i = 0; i < m; i++) {
int u = scanner.nextInt() - 1;
int v = scanner.nextInt() - 1;
if (u != v) {
g.addEdge(u, v);
g.addEdge(v, u);
}
}
ArrayList<Integer> seq = visit(g);
for (int i = 0; i < g.n - 1; i++) {
System.out.print((seq.get(i) + 1) + " ");
}
System.out.println(seq.get(g.n - 1) + 1);
}
public static ArrayList<Integer> visit(Graph g) {
int[] m = new int[g.n];
for (int i = 0; i < m.length; i++) {
m[i] = 0;
}
ArrayList<Integer> seq = new ArrayList<>();
recVisit(g, 0, m, seq);
return seq;
}
public static void recVisit(Graph g, int u, int[] m, ArrayList<Integer> seq) {
Integer next = u;
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.add(next);
while (seq.size() < g.n) {
Integer cur = queue.poll();
if (m[cur] == 0) {
seq.add(cur);
m[cur] = 1;
for (Integer e : g.edge.get(cur)) {
queue.add(e);
}
}
}
}
public static class Graph {
public int n;
public ArrayList<ArrayList<Integer>> edge;
public Graph(int n) {
this.n = n;
edge = new ArrayList<>();
for (int i = 0; i < n; i++) {
edge.add(new ArrayList<>());
}
}
public void addEdge(int u, int v) {
edge.get(u).add(v);
}
public int getIndex(int cur, int[] m) {
for (int i = 0; i < edge.get(cur).size(); i++) {
if (m[edge.get(cur).get(i)] == 0) {
return i;
}
}
return edge.get(cur).size();
}
}
}
| Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 37558de2119432f512936e479c421434 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.util.*;
import java.io.*;
import java.util.PriorityQueue;
public class lunaryear{
public static void main(String args[]) throws IOException {
Reader in = new Reader();
int n = in.nextInt();
int e = in.nextInt();
boolean visited[] = new boolean[n+1];
List<List<Integer>> edges = new ArrayList<List<Integer>>();
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for(int i=0;i<=n;i++) edges.add(new ArrayList<Integer>());
for(int i=0;i<e;i++){
int from = in.nextInt();
int to = in.nextInt();
edges.get(from).add(to);
edges.get(to).add(from);
}
pq.add(1);
while(!pq.isEmpty()){
int node = pq.poll();
if(!visited[node]){
System.out.print(node+" ");
visited[node] = true;
for(int neighbors:edges.get(node)){
if(!visited[neighbors]) pq.add(neighbors);
}
}
}
}
static class Reader{
private BufferedReader rd;
private StringTokenizer tk;
Reader(){
rd = new BufferedReader(new InputStreamReader(System.in));
tk = null;
}
public String next() {
while(tk==null || !tk.hasMoreElements()) {
try {
tk = new StringTokenizer(rd.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return tk.nextToken();
}
private int nextInt(){
return Integer.parseInt(next());
}
private double nextdouble() {
return Double.parseDouble(next());
}
private float nextfloat() {
return Float.parseFloat(next());
}
private int[] readArray(int n) {
int arr[] = new int[n];
for(int i=0;i<n;i++) arr[i] = nextInt();
return arr;
}
}
}
| Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 757655182a409550fd4db62be09dca51 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 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.PriorityQueue;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Stack;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
Task536D solver = new Task536D();
solver.solve(1, in, out);
out.close();
}
static class Task536D {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int visited[] = new int[n + 1];
ArrayList<Integer> ans = new ArrayList<>();
int i, j;
ArrayList<Integer> arr[] = new ArrayList[n + 1];
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (i = 0; i <= n; i++) {
arr[i] = new ArrayList<>();
}
for (i = 0; i < m; i++) {
int a = in.nextInt();
int b = in.nextInt();
arr[a].add(b);
arr[b].add(a);
}
pq.add(1);
while (ans.size() != n) {
int u = pq.poll();
if(visited[u] == 1) continue;
ans.add(u);
visited[u] = 1;
for(int x: arr[u])
{
if(visited[x] == 0)
pq.offer(x);
}
}
for (int x : ans) {
out.print(x + " ");
}
out.println();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int 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 static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
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() {
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 29ade402909b8dbce21be9e79a112734 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | //package sept;
import java.io.*;
import java.util.*;
public class TimePass implements Runnable {
InputStream is;
PrintWriter out;
String INPUT = "1 2";
//boolean debug=false;
boolean debug=true;
static long mod=998244353;
static long mod2=1000000007;
void solve() throws IOException
{
/*
int n=ni();
int m=ni();
int[] a=na(n);
int[] c=na(n);
PriorityQueue<Pair> pq=new PriorityQueue<>(new Comparator<Pair>() {
@Override
public int compare(Pair arg0, Pair arg1) {
// TODO Auto-generated method stub
if(arg0.a==arg1.a)return arg0.b-arg1.b;
return arg0.a-arg1.a;
}
});
for(int i=0;i<n;i++)
{
pq.add(new Pair(c[i],i));
}
for(int i=0;i<m;i++)
{
int kind=ni()-1,no=ni();
long cost=0;
if(a[kind]<no)
{
cost+=(long)a[kind]*c[kind];
//a[kind]=0;
int rem=no-a[kind];
a[kind]=0;
while(rem>0)
{
Pair curr=pq.peek();
if(curr==null)break;
int ind=curr.b;
if(a[ind]==0)pq.poll();
else if(a[ind]<rem)
{
//a[ind]=0;
cost+=((long)a[ind]*curr.a);
rem-=a[ind];
a[ind]=0;
pq.poll();
}
else
{
cost+=((long)rem*curr.a);
a[ind]-=rem;
rem=0;
if(a[ind]==0)pq.poll();
}
}
if(rem!=0)cost=0;
}
else
{
cost+=(long)no*c[kind];
a[kind]-=no;
}
//out.println(Arrays.toString(a));
out.println(cost);
}
*/
int n=ni(),m=ni();
int[] from=new int[2*m];
int[] to=new int[2*m];
int ind=0;
for(int i=0;i<m;i++)
{
int u=ni()-1,v=ni()-1;
if(u==v)continue;
from[ind++]=u;
to[ind-1]=v;
from[ind++]=v;
to[ind-1]=u;
}
int[][] g=packD(n,from,to);
set=new TreeSet<>();
set.add(0);
int[] vis=new int[n];
dfs(0,g,vis);
out.println();
}
static TreeSet<Integer> set;
private void dfs(int i, int[][] g, int[] vis) {
// TODO Auto-generated method stub
set.remove(i);
out.print((i+1)+" ");
vis[i]=1;
for(int v:g[i])
{
if(vis[v]==0)
{
set.add(v);
}
}
if(set.size()>0)
dfs(set.first(),g,vis);
}
static int[][] packD(int n,int[] from,int[] to)
{
int[][] g=new int[n][];
int[] p=new int[n];
for(int f:from)
{
p[f]++;
}
int m=from.length;
for(int i=0;i<n;i++)
{
g[i]=new int[p[i]];
}
for(int i=0;i<m;i++)
{
g[from[i]][--p[from[i]]]=to[i];
}
return g;
}
static class Pair
{
int a,b;
public Pair(int a,int b)
{
this.a=a;
this.b=b;
//this.ind=ind;
}
}
static long lcm(int a,int b)
{
long val=a;
val*=b;
return (val/gcd(a,b));
}
static long gcd(long a,long b)
{
if(a==0)return b;
return gcd(b%a,a);
}
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);
}
public void run()
{
if(debug)oj=true;
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
try {
solve();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception {new Thread(null,new TimePass(),"Main",1<<26).start();}
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 | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 2fef2fc7be20564f0abd0257cc2b0213 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Prob1106D {
public static class Graph {
private int vertices;
private ArrayList<Integer> adjList[];
Graph (int v) {
vertices = v;
adjList = new ArrayList[vertices + 1];
for (int i = 0; i < vertices+1; i++) {
adjList[i] = new ArrayList<Integer>();
}
}
public void addEdge(int src, int dest) {
adjList[src].add(dest);
adjList[dest].add(src);
}
public int numVertices() {
return vertices;
}
public boolean exists(int src, int dest) {
for (int i : adjList[src]) {
if (i == dest)
return true;
}
return false;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
Graph g = new Graph(n);
for (int i = 0; i < m; i++) {
int src = in.nextInt();
int dest = in.nextInt();
if (src == dest)
continue;
// if (g.exists(src, dest))
// continue;
g.addEdge(src, dest);
}
ArrayList<Integer> path = new ArrayList<Integer>();
HashSet<Integer> seen = new HashSet<Integer>();
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
pq.add(1);
seen.add(1);
while (!pq.isEmpty()) {
int node = pq.poll();
for (int i : g.adjList[node]) {
if (seen.contains(i))
continue;
seen.add(i);
pq.add(i);
}
path.add(node);
}
System.out.print(path.get(0));
for (int i = 1; i < path.size(); i++) {
System.out.print(" " + path.get(i));
}
}
}
| Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | d73e8cbda30c6d8f211ec4c5b95dbdfb | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | //package year2019.month01.cf.round536;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
public class TaskD {
boolean ONLINE_JUDGE = (System.getProperty("ONLINE_JUDGE") != null);
public TaskD() throws IOException {
InputReader in;
if (ONLINE_JUDGE) {
in = new InputReader(System.in);
} else {
in = new InputReader(new FileInputStream("/Users/karj/Competitive Programming/input.txt"));
}
PrintWriter out = new PrintWriter(System.out);
int T = 1;
for (int caseNo = 1; caseNo <= T; caseNo++) {
solve(caseNo, in, out);
}
out.close();
}
private void solve(int caseNo, InputReader in, PrintWriter out) throws IOException {
int N = in.nextInteger(), M = in.nextInteger();
ArrayList<Integer> graph[] = new ArrayList[N];
visited = new boolean[N];
for (int i = 0; i < N; i++) {
graph[i] = new ArrayList<>();
}
for (int i = 0; i < M; i++) {
int u = in.nextInteger() - 1, v = in.nextInteger() - 1;
graph[u].add(v);
graph[v].add(u);
}
TreeSet<Integer> next = new TreeSet<>();
next.add(0);
int idx = 0;
int order[] = new int[N];
// String seq = dfs(0, graph, next, idx, order);
// out.println(seq);
dfs(0, graph, next, idx, order);
for (int o : order) {
out.print(o + " ");
}
}
boolean visited[];
private void dfs(int u, ArrayList<Integer>[] graph, TreeSet<Integer> next, int idx, int[] order) {
visited[u] = true;
// StringBuilder seq = new StringBuilder();
// seq.append((u + 1) + " ");
order[idx] = u + 1;
for (int v : graph[u]) {
if (!visited[v]) {
next.add(v);
}
}
while (!next.isEmpty()) {
int vv = next.pollFirst();
if (!visited[vv]) {
// seq.append(dfs(vv, graph, next, idx + 1, order));
dfs(vv, graph, next, idx + 1, order);
}
}
// return seq.toString();
return;
}
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 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 boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public String next() {
return nextString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public int nextInteger() {
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() {
return Long.parseLong(nextString());
}
public Double nextDouble() {
return Double.parseDouble(nextString());
}
public char nextCharacter() {
return nextString().charAt(0);
}
}
private void debug(Object... o) {
if (ONLINE_JUDGE) {
return;
}
System.out.println(Arrays.deepToString(o));
}
public static void main(String args[]) throws IOException {
new TaskD();
}
}
| Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | ffcd724ba5d78ac997fc533d24cb8015 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class gfg {
static int n;
static int m;
static TreeSet<Integer>[] graph;
static boolean[] vis ;
static ArrayList<Integer> list = new ArrayList<>();
static void solve()throws IOException{
n = Reader.nextInt();
m =Reader.nextInt();
graph = new TreeSet[n+1];
vis = new boolean[n+1];
for(int i=1;i<=n;i++)
graph[i] = new TreeSet<Integer>();
for(int i=1;i<=m;i++){
int a = Reader.nextInt();
int b = Reader.nextInt();
graph[a].add(b);
graph[b].add(a);
}
bfs();
}
static void bfs(){
TreeSet<Integer> pq = new TreeSet<>();
pq.add(1);
while(pq.size()>0){
int a = pq.pollFirst();
System.out.print(a+" ");
if(!vis[a]){
vis[a]=true;
while(graph[a].size()>0){
int x = graph[a].pollFirst();
if(!vis[x]){
pq.add(x);
}
}
}
}
}
public static void main(String[] args) throws IOException{
Reader.init(System.in);
int t = 1;//Reader.nextInt();
while(t-->0){
solve();
}
}
// ggratest common divisor
static int gcd(int a , int b){
if(b==0)
return a;
else
return gcd(b,a%b);
}
// least common multiple
static int lcm(int a, int b){
return (a*b)/gcd(a,b);
}
// a^b
static long fastpow(long a, long n){
//System.out.println("ssdf");
if(n>0){
long half = fastpow(a,n/2);
if(n%2==0){
return half*half;
}
else
return a*half*half;
}
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 newcomparator implements Comparator<Integer>{
//@Override
public int compare(Integer a, Integer b){
return a<=b?1:-1;
}
}
class node {
int a;
long b;// cost to rreach\
node(int s,long va){
a=s;
b=va;
}
}
class mergesort{
static void sort(int l, int h, int[] arr){
if(l<h){
int mid = (l+h)/2;
sort(l,mid,arr);
sort(mid+1,h,arr);
merge(l,mid,h,arr);
}
}
static void merge(int l, int m , int h , int [] arr){
int[] left = new int[m-l+1];
int[] right = new int[h-m];
for(int i= 0 ;i< m-l+1;i++){
left[i] = arr[l+i];
}
for(int i=0;i<h-m;i++){
right[i] = arr[m+1+i];
}
//now left and right arrays are assumed to be sorted and we have tp merge them together
// int the original aaray.
int i=l;
int lindex = 0;
int rindex = 0;
while(lindex<m-l+1 && rindex<h-m){
if(left[lindex]<=right[rindex]){
arr[i]=left[lindex];
lindex++;
i++;
}
else{
arr[i]=right[rindex];
rindex++;
i++;
}
}
while(lindex<m-l+1){
arr[i]=left[lindex];
lindex++;
i++;
}
while(rindex<h-m){
arr[i]=right[rindex];
rindex++;
i++;
}
}
} | Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | f82ae5c237e639efce1bc916f5482917 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class gfg {
static int n;
static int m;
static ArrayList<Integer>[] graph;
static boolean[] vis ;
static ArrayList<Integer> list = new ArrayList<>();
static void solve()throws IOException{
n = Reader.nextInt();
m =Reader.nextInt();
graph = new ArrayList[n+1];
vis = new boolean[n+1];
for(int i=1;i<=n;i++)
graph[i] = new ArrayList<Integer>();
for(int i=1;i<=m;i++){
int a = Reader.nextInt();
int b = Reader.nextInt();
graph[a].add(b);
graph[b].add(a);
}
bfs();
}
static void bfs(){
TreeSet<Integer> pq = new TreeSet<>();
pq.add(1);
while(pq.size()>0){
int a = pq.pollFirst();
System.out.print(a+" ");
if(!vis[a]){
vis[a]=true;
for(int i=0;i<graph[a].size();i++){
int x = graph[a].get(i);
if(!vis[x]){
pq.add(x);
}
}
}
}
}
public static void main(String[] args) throws IOException{
Reader.init(System.in);
int t = 1;//Reader.nextInt();
while(t-->0){
solve();
}
}
// ggratest common divisor
static int gcd(int a , int b){
if(b==0)
return a;
else
return gcd(b,a%b);
}
// least common multiple
static int lcm(int a, int b){
return (a*b)/gcd(a,b);
}
// a^b
static long fastpow(long a, long n){
//System.out.println("ssdf");
if(n>0){
long half = fastpow(a,n/2);
if(n%2==0){
return half*half;
}
else
return a*half*half;
}
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 newcomparator implements Comparator<Integer>{
//@Override
public int compare(Integer a, Integer b){
return a<=b?1:-1;
}
}
class node {
int a;
long b;// cost to rreach\
node(int s,long va){
a=s;
b=va;
}
}
class mergesort{
static void sort(int l, int h, int[] arr){
if(l<h){
int mid = (l+h)/2;
sort(l,mid,arr);
sort(mid+1,h,arr);
merge(l,mid,h,arr);
}
}
static void merge(int l, int m , int h , int [] arr){
int[] left = new int[m-l+1];
int[] right = new int[h-m];
for(int i= 0 ;i< m-l+1;i++){
left[i] = arr[l+i];
}
for(int i=0;i<h-m;i++){
right[i] = arr[m+1+i];
}
//now left and right arrays are assumed to be sorted and we have tp merge them together
// int the original aaray.
int i=l;
int lindex = 0;
int rindex = 0;
while(lindex<m-l+1 && rindex<h-m){
if(left[lindex]<=right[rindex]){
arr[i]=left[lindex];
lindex++;
i++;
}
else{
arr[i]=right[rindex];
rindex++;
i++;
}
}
while(lindex<m-l+1){
arr[i]=left[lindex];
lindex++;
i++;
}
while(rindex<h-m){
arr[i]=right[rindex];
rindex++;
i++;
}
}
} | Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 34c3cf75be623dfbc1e5ab5493a5e816 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main {
static int n, m;
static boolean[] was;
static TreeSet<Integer>[] mx;
static ArrayList<Integer> ans;
public static void main(String args[]) throws Exception {
init();
n = nextInt();
m = nextInt();
was = new boolean[n];
ans = new ArrayList<>();
mx = new TreeSet[n];
for (int i = 0; i < n; i++) {
mx[i] = new TreeSet<>();
}
for (int i = 0; i < m; i++) {
int from = nextInt() - 1,
to = nextInt() - 1;
mx[from].add(to);
mx[to].add(from);
}
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(0);
int ct = 0;
while (!pq.isEmpty() && ct != n){
int i = pq.remove();
if (was[i])
continue;
was[i] = true;
ans.add(i);
ct++;
for (int j : mx[i])
if (!was[j])
pq.add(j);
}
ans.forEach(i -> out.print((i + 1) + " "));
out.close();
}
static BufferedReader scan;
static PrintWriter out;
static StringTokenizer st;
static void init() {
scan = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
static void init(String name1, String name2) throws Exception {
try {
scan = new BufferedReader(new FileReader(name1));
out = new PrintWriter(name2);
} catch (Exception e) {
scan = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
}
static String next() throws Exception {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(scan.readLine());
return st.nextToken();
}
static int nextInt() throws Exception {
return Integer.parseInt(next());
}
static long nextLong() throws Exception {
return Long.parseLong(next());
}
} | Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 55b6750ea84cbf6cfab33a755ffc6936 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class fast 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);
}
}
class pair implements Comparable<pair>{
int x;
int y;
pair(int xi, int yi){
x=xi;
y=yi;
}
@Override
public int compareTo(pair other){
if(this.x>other.x){return 1;}
if(this.x<other.x){return -1;}
return 0;
}
}
class dist{
int x;
int y;
int z;
dist(int xi, int yi, int zi){
x=xi;
y=yi;
z=zi;
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new fast(),"fast",1<<26).start();
}
public void sortbyColumn(int arr[][], final int col){
// Using built-in sort function Arrays.sort
Arrays.sort(arr, new Comparator<int[]>() {
@Override
// Compare values according to columns
public int compare(final int[] entry1,
final int[] entry2) {
// To sort in descending order revert
// the '>' Operator
if (entry1[col] > entry2[col])
return 1;
else if(entry1[col] < entry2[col])
return -1;
return 0;
}
}); // End of function call sort().
}
public void sortbyColumn(long arr[][], final int col){
// Using built-in sort function Arrays.sort
Arrays.sort(arr, new Comparator<long[]>() {
@Override
// Compare values according to columns
public int compare(final long[] entry1,
final long[] entry2) {
// To sort in descending order revert
// the '>' Operator
if (entry1[col] > entry2[col])
return 1;
else if(entry1[col] < entry2[col])
return -1;
return 0;
}
}); // End of function call sort().
}
long power(long x, long y, long p){
long res = 1;
x = x % p;
while (y > 0)
{
if((y & 1)==1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public void run(){
InputReader s = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n=s.nextInt(),m=s.nextInt(),cnt=0,pos[]=new int[n];
ArrayList<Integer> a[]=new ArrayList[n];
boolean vis[]=new boolean[n];
Arrays.fill(pos,-1);
vis[0]=true;
for(int i=0;i<n;i++){
a[i]=new ArrayList<>();
}
for(int i=0;i<m;i++){
int x=s.nextInt()-1,y=s.nextInt()-1;
a[x].add(y);
a[y].add(x);
}
for(int i=0;i<n;i++){Collections.sort(a[i]);}
PriorityQueue<Integer> pq=new PriorityQueue<>();
pq.add(0);
while(!pq.isEmpty()){
int p=pq.poll(),x=0;
w.print((p+1)+" ");
while(x<a[p].size()){
//w.print(p.x+" "+pos[p.x]+" "+a[p.x].get(pos[p.x]));
if(!vis[a[p].get(x)]){
pq.add(a[p].get(x));
vis[a[p].get(x)]=true;
}
x++;
}
}
w.close();
}
} | Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | b0e94e3d9a913c41ad36a0d955d12b6a | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.util.*;
import java.io.*;
/**
*
* @author macbookpro
*/
public class D1106 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
ArrayList<Integer> adj[]= new ArrayList[n];
for (int i = 0; i < n; i++)
adj[i] = new ArrayList<Integer>();
for ( int i =0; i<m; i++)
{
st = new StringTokenizer(br.readLine());
int in = Integer.parseInt(st.nextToken())-1;
int out = Integer.parseInt(st.nextToken())-1;
adj[in].add(out);
adj[out].add(in);
}
TreeSet<Integer> ts = new TreeSet<>();
ts.add(0);
boolean used[] = new boolean[n];
used[0]=true;
Integer c;
StringBuilder sb = new StringBuilder();
while(( c =ts.pollFirst())!=null)
{
sb.append(c+1 +" ");
ArrayList<Integer> aa = adj[c];
for(int k:aa)
{
if(!used[k])
{ used[k]=true;
ts.add(k);
}
}
}
System.out.println(sb);
}
} | Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 3efe6c8b539654b58b17fb7ae4e45387 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
public class ProblemD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
@SuppressWarnings("unchecked")
Set<Integer>[] adj = new HashSet[n];
for(int i = 0; i < n; i++) {
adj[i] = new HashSet<Integer>();
}
for(int i = 0; i < m; i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
if(u == v) continue;
adj[u].add(v);
adj[v].add(u);
}
sc.close();
Queue<Integer> pq = new PriorityQueue<Integer>();
boolean[] vis = new boolean[n];
for(int i = 0; i < n; i++) {
vis[i] = true;
}
for(int u : adj[0]) {
pq.add(u);
}
int idx = 1;
int[] a = new int[n];
a[0] = 1;
vis[0] = false;
while(!pq.isEmpty()) {
int u = pq.poll();
if(!vis[u]) continue;
vis[u] = false;
a[idx] = u + 1;
for(int v : adj[u]) {
if(vis[v]) {
pq.add(v);
}
}
idx++;
if(idx == n) break;
}
for(int i = 0; i < n; i++) {
if(i == n - 1) {
System.out.println(a[i]);
}else {
System.out.print(a[i] +" ");
}
}
}
} | Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 844dd67726171f489736927c885c95d1 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
public class ProblemD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
@SuppressWarnings("unchecked")
Set<Integer>[] adj = new HashSet[n];
for(int i = 0; i < n; i++) {
adj[i] = new HashSet<Integer>();
}
for(int i = 0; i < m; i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
if(u == v) continue;
adj[u].add(v);
adj[v].add(u);
}
sc.close();
Queue<Integer> pq = new PriorityQueue<Integer>();
boolean[] vis = new boolean[n];
for(int i = 0; i < n; i++) {
vis[i] = true;
}
for(int u : adj[0]) {
pq.add(u);
vis[u] = false;
}
int idx = 1;
int[] a = new int[n];
a[0] = 1;
vis[0] = false;
while(!pq.isEmpty()) {
int u = pq.poll();
a[idx] = u + 1;
for(int v : adj[u]) {
if(vis[v]) {
pq.add(v);
vis[v] = false;
}
}
idx++;
if(idx == n) break;
}
for(int i = 0; i < n; i++) {
if(i == n - 1) {
System.out.println(a[i]);
}else {
System.out.print(a[i] +" ");
}
}
}
} | Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | fb8ed4ce8ca010a550096735e5ff3483 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Lunarwander 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);
}
}
static int n,m;
static ArrayList<Integer> al[],ans;
static boolean visited[];
static void dfs(int node)
{
visited[node]=true;
ans.add(node);
for(int child:al[node]) if(!visited[child]) dfs(child);
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Lunarwander(),"Lunarwander",1<<27).start();
}
// **just change the name of class from Main to reuquired**
public void run()
{
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
n=sc.nextInt();
m=sc.nextInt();
al=new ArrayList[n+1];
for(int i=0;i<=n;++i) al[i]=new ArrayList<Integer>();
visited=new boolean[n+1];
ans=new ArrayList<Integer>();
while(m-->0)
{
int u=sc.nextInt(),v=sc.nextInt();
al[u].add(v);
al[v].add(u);
}
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(1);
visited[1]=true;
while(!pq.isEmpty())
{
int v=pq.poll();
w.print(v+" ");
for(int u:al[v])
{
if(!visited[u])
{
visited[u]=true;
pq.add(u);
}
}
}
System.out.flush();
w.close();
}
} | Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 55ed9cf0422e187960609de0dd5c7ce8 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.io.PrintWriter;
import java.util.*;
public class Arsen {
static ArrayList<Integer>[] gr;
static boolean[] was;
static Queue<Integer> q;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int m = in.nextInt();
gr = new ArrayList[n];
was = new boolean[n];
q = new LinkedList<>();
for (int i = 0; i < n; i++) {
gr[i] = new ArrayList();
}
for (int i = 0; i < m; i++) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
gr[x].add(y);
gr[y].add(x);
}
for (int i = 0; i < n; i++) {
Collections.sort(gr[i]);
}
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(0);
while (!pq.isEmpty()) {
int v = pq.poll();
if(was[v])
continue;
q.add(v);
was[v] = true;
for (Integer to : gr[v]) {
if (!was[to]) {
pq.add(to);
}
}
}
for (int i = 0; i < n; i++) {
out.print(q.poll() + 1 + " ");
}
out.close();
}
}
class f {
int v;
int type;
public f(int v, int type) {
this.v = v;
this.type = type;
}
} | Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | e6e0ca033197c97a3a09101004597bfc | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class LunearYearAndWander {
public static void main(String[] args) {
// TODO Auto-generated method stub
FastScanner input= new FastScanner();
int n = input.nextInt();
int m = input.nextInt();
list =new ArrayList[n];
for(int i=0; i<n;i++){
list[i] = new ArrayList<Integer>();
}
for(int i=0; i<m;i++){
int a = input.nextInt()-1;
int b = input.nextInt()-1;
list[a].add(b);
list[b].add(a);
}
used =new boolean[n];
used[0] = true;
TreeSet<Integer> pq = new TreeSet<>();
pq.add(0);
Integer i_;
StringBuilder sb = new StringBuilder();
while ((i_ = pq.pollFirst()) != null) {
sb.append((i_ + 1) + " ");
ArrayList<Integer> aa = list[i_];
for (int j : aa) {
if (!used[j]) {
used[j] = true;
pq.add(j);
}
}
}
System.out.println(sb);
}
static boolean[] used;
static ArrayList<Integer>[] list;
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new FileReader("testdata.out"));
st = new StringTokenizer("");
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
try {line = br.readLine();}
catch (Exception e) {e.printStackTrace();}
return line;
}
public Integer[] nextIntegerArray(int n) {
Integer[] a = new Integer[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public char[] nextCharArray() {
return nextLine().toCharArray();
}
}
}
| Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 316cc7121ac24f14a7fcb03bc2daaecb | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.util.*;
public class Main {
public List<Integer> bfs(Map<Integer, List<Integer>> graph) {
TreeSet<Integer> bfsQ = new TreeSet<>();
Set<Integer> visited = new HashSet<>();
List<Integer> order = new ArrayList<>();
bfsQ.add(1);
visited.add(1);
while (!bfsQ.isEmpty()) {
int size = bfsQ.size();
for (int i = 0; i < size; i++) {
Integer node = bfsQ.pollFirst();
order.add(node);
List<Integer> neighbors = graph.get(node);
for (Integer neighbor : neighbors) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
bfsQ.add(neighbor);
}
}
}
}
return order;
}
public static void main(String[] args) {
Main main = new Main();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
Map<Integer, List<Integer>> graph = new HashMap<>();
for (int i = 1; i <= n; i++)
graph.put(i, new ArrayList<>());
for (int i = 0; i < m; i++) {
int from = sc.nextInt();
int to = sc.nextInt();
graph.get(from).add(to);
graph.get(to).add(from);
}
List<Integer> order = main.bfs(graph);
for (Integer element : order)
System.out.print(element + " ");
System.out.println();
}
} | Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 92ac1a2a573163c05ca87cf0ad0637b1 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | //package cdchf;
import java.util.*;
public class d1106 {
static void addEdge(ArrayList<ArrayList<Integer>> adj,int a,int b) {
adj.get(a).add(b);
adj.get(b).add(a);
}
static void solver(int s,ArrayList<ArrayList<Integer>> adj,boolean visited[],ArrayList<Integer> result,PriorityQueue<Integer> maxHeap) {
visited[s]=true;
maxHeap.add(s);
while(maxHeap.isEmpty()!=true) {
int t = maxHeap.poll();
//result.add(t+1);
System.out.print((t+1)+ " ");
for(int i:adj.get(t)) {
if(visited[i]==false) {
visited[i]=true;
maxHeap.add(i);
}
}
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
});
ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(n);
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<Integer>());
}
int m = s.nextInt();
for(int i=0;i<m;i++) {
int t1 = s.nextInt()-1;
int t2 = s.nextInt()-1;
addEdge(adj,t1,t2);
}
boolean visited[] = new boolean[n];
ArrayList<Integer> result = new ArrayList<Integer>();
solver(0,adj,visited,result,maxHeap);
}
}
| Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 9ddbd32f5b6d19c4cffb951a318dd568 | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.util.*;
public class Main
{
static LinkedList<Integer> adj[];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
adj = new LinkedList[n];
for(int i=0;i<n;i++)adj[i] = new LinkedList<>();
for(int i=0;i<m;i++)
{
int a = sc.nextInt();
int b = sc.nextInt();
adj[a-1].add(b-1);
adj[b-1].add(a-1);
}
bfs(0,n);
}
public static void bfs(int v,int s)
{
PriorityQueue<Integer> q = new PriorityQueue<>();
boolean b[] = new boolean[s];
q.add(v);
b[v]=true;
while(!q.isEmpty())
{
v = q.poll();
System.out.print(v+1+" ");
Iterator<Integer> itr = adj[v].listIterator();
while(itr.hasNext())
{
int n = itr.next();
if(!b[n])
{
q.add(n);
b[n] = true;
}
}
}
}
} | Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 0daad0af3342eb7cfdc6c33cf6ff7c6b | train_004.jsonl | 1548938100 | Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.The park can be represented as a connected graph with $$$n$$$ nodes and $$$m$$$ bidirectional edges. Initially Bob is at the node $$$1$$$ and he records $$$1$$$ on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes $$$a_1, a_2, \ldots, a_n$$$ is recorded.Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.A sequence $$$x$$$ is lexicographically smaller than a sequence $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$ (this is impossible in this problem as all considered sequences have the same length); in the first position where $$$x$$$ and $$$y$$$ differ, the sequence $$$x$$$ has a smaller element than the corresponding element in $$$y$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class LunarNewYear {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
ArrayList<Integer> list[] = new ArrayList[n + 1];
for (int i = 1; i <= n; i++)
list[i] = new ArrayList<>();
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int i = 1; i <= m; i++) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
list[u].add(v);
list[v].add(u);
}
pq.add(1);
StringBuilder sb = new StringBuilder();
boolean visited[] = new boolean[n + 1];
while (!pq.isEmpty()) {
int node = pq.remove();
if (visited[node])
continue;
visited[node] = true;
sb.append(node + " ");
for (int neighbour : list[node]) {
if (visited[neighbour])
continue;
pq.add(neighbour);
}
}
System.out.println(sb);
}
}
| Java | ["3 2\n1 2\n1 3", "5 5\n1 4\n3 4\n5 4\n3 2\n1 5", "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10"] | 3 seconds | ["1 2 3", "1 4 3 2 5", "1 4 3 7 9 8 6 5 2 10"] | NoteIn the first sample, Bob's optimal wandering path could be $$$1 \rightarrow 2 \rightarrow 1 \rightarrow 3$$$. Therefore, Bob will obtain the sequence $$$\{1, 2, 3\}$$$, which is the lexicographically smallest one.In the second sample, Bob's optimal wandering path could be $$$1 \rightarrow 4 \rightarrow 3 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 5$$$. Therefore, Bob will obtain the sequence $$$\{1, 4, 3, 2, 5\}$$$, which is the lexicographically smallest one. | Java 8 | standard input | [
"greedy",
"graphs",
"shortest paths",
"data structures",
"dfs and similar"
] | 157630371c4f6c3bcc6355d96c86a626 | The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$), denoting the number of nodes and edges, respectively. The following $$$m$$$ lines describe the bidirectional edges in the graph. The $$$i$$$-th of these lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), representing the nodes the $$$i$$$-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. | 1,500 | Output a line containing the lexicographically smallest sequence $$$a_1, a_2, \ldots, a_n$$$ Bob can record. | standard output | |
PASSED | 3ff4481c80e1ec7c1999eea1b28b80cd | train_004.jsonl | 1603623900 | Meka-Naruto plays a computer game. His character has the following ability: given an enemy hero, deal $$$a$$$ instant damage to him, and then heal that enemy $$$b$$$ health points at the end of every second, for exactly $$$c$$$ seconds, starting one second after the ability is used. That means that if the ability is used at time $$$t$$$, the enemy's health decreases by $$$a$$$ at time $$$t$$$, and then increases by $$$b$$$ at time points $$$t + 1$$$, $$$t + 2$$$, ..., $$$t + c$$$ due to this ability.The ability has a cooldown of $$$d$$$ seconds, i. e. if Meka-Naruto uses it at time moment $$$t$$$, next time he can use it is the time $$$t + d$$$. Please note that he can only use the ability at integer points in time, so all changes to the enemy's health also occur at integer times only.The effects from different uses of the ability may stack with each other; that is, the enemy which is currently under $$$k$$$ spells gets $$$k\cdot b$$$ amount of heal this time. Also, if several health changes occur at the same moment, they are all counted at once.Now Meka-Naruto wonders if he can kill the enemy by just using the ability each time he can (that is, every $$$d$$$ seconds). The enemy is killed if their health points become $$$0$$$ or less. Assume that the enemy's health is not affected in any way other than by Meka-Naruto's character ability. What is the maximal number of health points the enemy can have so that Meka-Naruto is able to kill them? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class a {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(reader.readLine());
for(int q = 0; q < t; ++q){
StringTokenizer st = new StringTokenizer(reader.readLine());
long a = Long.parseLong(st.nextToken());
long b = Long.parseLong(st.nextToken());
long c = Long.parseLong(st.nextToken());
long d = Long.parseLong(st.nextToken());
if(a > b * c){
System.out.println(-1);
continue;
}
long k = a / b / d;
System.out.println(a * (k + 1) - (k + 1) * k / 2 * b * d);
}
}
}
| Java | ["7\n1 1 1 1\n2 2 2 2\n1 2 3 4\n4 3 2 1\n228 21 11 3\n239 21 11 3\n1000000 1 1000000 1"] | 1 second | ["1\n2\n1\n5\n534\n-1\n500000500000"] | NoteIn the first test case of the example each unit of damage is cancelled in a second, so Meka-Naruto cannot deal more than 1 damage.In the fourth test case of the example the enemy gets: $$$4$$$ damage ($$$1$$$-st spell cast) at time $$$0$$$; $$$4$$$ damage ($$$2$$$-nd spell cast) and $$$3$$$ heal ($$$1$$$-st spell cast) at time $$$1$$$ (the total of $$$5$$$ damage to the initial health); $$$4$$$ damage ($$$3$$$-nd spell cast) and $$$6$$$ heal ($$$1$$$-st and $$$2$$$-nd spell casts) at time $$$2$$$ (the total of $$$3$$$ damage to the initial health); and so on. One can prove that there is no time where the enemy gets the total of $$$6$$$ damage or more, so the answer is $$$5$$$. Please note how the health is recalculated: for example, $$$8$$$-health enemy would not die at time $$$1$$$, as if we first subtracted $$$4$$$ damage from his health and then considered him dead, before adding $$$3$$$ heal.In the sixth test case an arbitrarily healthy enemy can be killed in a sufficient amount of time.In the seventh test case the answer does not fit into a 32-bit integer type. | Java 11 | standard input | [
"greedy",
"ternary search",
"math"
] | 570b8bfd5f860ee2b258fdbb0d6e20ce | The first line contains an integer $$$t$$$ ($$$1\leq t\leq 10^5$$$) standing for the number of testcases. Each test case is described with one line containing four numbers $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ ($$$1\leq a, b, c, d\leq 10^6$$$) denoting the amount of instant damage, the amount of heal per second, the number of heals and the ability cooldown, respectively. | 2,100 | For each testcase in a separate line print $$$-1$$$ if the skill can kill an enemy hero with an arbitrary number of health points, otherwise print the maximal number of health points of the enemy that can be killed. | standard output | |
PASSED | f57534581bd1ab1a7e738dad1df4b8df | train_004.jsonl | 1293552000 | According to the last order issued by the president of Berland every city of the country must have its own Ministry Defense building (their own Pentagon). A megapolis Berbourg was not an exception. This city has n junctions, some pairs of which are connected by two-way roads. Overall there are m roads in the city, no more than one between each pair of junctions.At the moment choosing a location place for Pentagon in Berbourg is being discussed. It has been decided that Pentagon should cover the territory of five different junctions which are joined into a cycle by roads. In the order to build Pentagon a special wall will be built along the roads (with high-tension razor, high-voltage wire and other attributes). Thus, the number of possible ways of building Pentagon in the city is equal to the number of different cycles at lengths of 5, composed of junctions and roads.Your task is to prints the number of ways of building Pentagon in Berbourg. Only well-optimized solutions will be accepted. Please, test your code on the maximal testcase. | 256 megabytes | import java.util.*;
import java.io.*;
public class E {
public static void main(String[] args) throws Exception{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer stok = new StringTokenizer(in.readLine());
N = Integer.valueOf(stok.nextToken());
M = Integer.valueOf(stok.nextToken());
G = new ArrayList[N];
for(int i = 0; i < N;i++){
G[i] = new ArrayList<Integer>();
}
for(int i = 0; i < M;i++){
stok = new StringTokenizer(in.readLine());
int a = Integer.valueOf(stok.nextToken())-1;
int b = Integer.valueOf(stok.nextToken())-1;
G[a].add(b);
G[b].add(a);
}
for(int i = 0; i < N;i++)
Collections.sort(G[i]);
long ans = solve();
System.out.println(ans);
// Random R = new Random(24343L);
// for(int z = 0; z < 100;z++){
// N = 100;
// G = new ArrayList[N];
// for(int i = 0; i < N;i++)
// G[i] = new ArrayList<Integer>();
// for(int i = 0; i < N;i++)
// for(int j = i+1; j < N;j++)
// if(R.nextInt(10) == 0){
// G[i].add(j);
// G[j].add(i);
// }
// long ans = solve();
// long ans2 = solve2();
// if(ans != ans2){
// System.out.println("ERROR!");
// System.out.println(ans+" "+ans2);
// for(int i = 0; i < N;i++)
// System.out.println(G[i]);
// System.exit(0);
// }
// System.out.println(ans+" "+ans2);
// }
}
private static long solve2() {
long ans = 0;
for(int i = 0; i < N;i++)
ans += dfs(i,i,5, new boolean[N]);
return ans/10;
}
private static long dfs(int at, int end, int left, boolean[] V) {
if(left == 0)
return at == end ? 1:0;
long ans = 0;
for(int e:G[at]){
if(V[e])
continue;
V[e] = true;
ans += dfs(e, end, left-1, V);
V[e] = false;
}
return ans;
}
static ArrayList<Integer>[] G;
static int N, M;
static long solve(){
boolean[][] C = new boolean[N][N];
long[] D = new long[N];
for(int i = 0; i < N;i++)
D[i] = G[i].size();
for(int i = 0; i < N;i++)
for(int e: G[i])
C[i][e] = true;
long[][] P = new long[N][N];
long ans = 0;
for(int i = 0; i < N;i++)
for(int j = 0; j < N;j++)
for(int k = 0; k < N;k++){
if(C[i][j] && C[j][k] && i != k)
P[i][k]++;
if(C[i][k] && C[i][j] && C[j][k]){
ans -= D[j]-2;
}
}
for(int i = 0; i < N;i++){
for(int j = 0; j < N;j++){
for(int k = 0; k < N;k++){
if(C[i][k] && i != j && j != k){
long l = P[i][j]-(C[j][k]?1:0);
long r = P[j][k]-(C[i][j]?1:0);
ans += l*r;
}
}
}
}
return ans/10;
}
}
| Java | ["5 5\n1 2\n2 3\n3 4\n4 5\n5 1", "5 10\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 10 seconds | ["1", "12"] | null | Java 6 | standard input | [
"combinatorics",
"graphs",
"matrices"
] | 74d9bb152295cb30315f6444906dd891 | The first line contains two integers n and m (1 ≤ n ≤ 700;0 ≤ m ≤ n·(n - 1) / 2), where n represents the number of junctions and m is the number of roads in the city. Then follow m lines containing the road descriptions, one in each line. Every road is set by a number of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi), where ai and bi represent the numbers of junctions, connected by the road. The junctions are numbered from 1 to n. It is not guaranteed that from any junction one can get to any other one moving along the roads. | 2,400 | Print the single number which represents the required number of ways. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | ebc12289e2b553941f089792750ed96e | train_004.jsonl | 1293552000 | According to the last order issued by the president of Berland every city of the country must have its own Ministry Defense building (their own Pentagon). A megapolis Berbourg was not an exception. This city has n junctions, some pairs of which are connected by two-way roads. Overall there are m roads in the city, no more than one between each pair of junctions.At the moment choosing a location place for Pentagon in Berbourg is being discussed. It has been decided that Pentagon should cover the territory of five different junctions which are joined into a cycle by roads. In the order to build Pentagon a special wall will be built along the roads (with high-tension razor, high-voltage wire and other attributes). Thus, the number of possible ways of building Pentagon in the city is equal to the number of different cycles at lengths of 5, composed of junctions and roads.Your task is to prints the number of ways of building Pentagon in Berbourg. Only well-optimized solutions will be accepted. Please, test your code on the maximal testcase. | 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.StringTokenizer;
public class E {
static StringTokenizer st;
static BufferedReader in;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int m = nextInt();
boolean[][]a = new boolean[n+1][n+1];
for (int i = 1; i <= m; i++) {
int v1 = nextInt();
int v2 = nextInt();
a[v1][v2] = a[v2][v1] = true;
}
int[][]cnt = new int[n+1][n+1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
for (int j2 = 1; j2 <= n; j2++) {
if (a[i][j2] && a[j][j2]) {
cnt[i][j]++;
}
}
}
}
int[]g = new int[n+1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (a[i][j])
g[i]++;
}
}
long ans = 0;
for (int i = 1; i <= n; i++) {
for (int j = i+1; j <= n; j++) {
if (a[i][j]) {
for (int j2 = 1; j2 <= n; j2++) {
if (j2 != i && j2 != j) {
ans += cnt[i][j2]*cnt[j][j2];
if (a[i][j2])
ans -= cnt[i][j2];
if (a[j][j2])
ans -= cnt[j][j2];
if (a[i][j2] && a[j][j2])
ans++;
}
}
for (int j2 = 1; j2 <= n; j2++) {
if (a[i][j2] && a[j][j2])
ans -= g[j2]-2;
}
}
}
}
System.out.println(ans/5);
pw.close();
}
private static int nextInt() throws IOException{
return Integer.parseInt(next());
}
private static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
}
| Java | ["5 5\n1 2\n2 3\n3 4\n4 5\n5 1", "5 10\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 10 seconds | ["1", "12"] | null | Java 6 | standard input | [
"combinatorics",
"graphs",
"matrices"
] | 74d9bb152295cb30315f6444906dd891 | The first line contains two integers n and m (1 ≤ n ≤ 700;0 ≤ m ≤ n·(n - 1) / 2), where n represents the number of junctions and m is the number of roads in the city. Then follow m lines containing the road descriptions, one in each line. Every road is set by a number of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi), where ai and bi represent the numbers of junctions, connected by the road. The junctions are numbered from 1 to n. It is not guaranteed that from any junction one can get to any other one moving along the roads. | 2,400 | Print the single number which represents the required number of ways. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | 3b445124ec96fc57d0b860d9134c8f4a | train_004.jsonl | 1293552000 | According to the last order issued by the president of Berland every city of the country must have its own Ministry Defense building (their own Pentagon). A megapolis Berbourg was not an exception. This city has n junctions, some pairs of which are connected by two-way roads. Overall there are m roads in the city, no more than one between each pair of junctions.At the moment choosing a location place for Pentagon in Berbourg is being discussed. It has been decided that Pentagon should cover the territory of five different junctions which are joined into a cycle by roads. In the order to build Pentagon a special wall will be built along the roads (with high-tension razor, high-voltage wire and other attributes). Thus, the number of possible ways of building Pentagon in the city is equal to the number of different cycles at lengths of 5, composed of junctions and roads.Your task is to prints the number of ways of building Pentagon in Berbourg. Only well-optimized solutions will be accepted. Please, test your code on the maximal testcase. | 256 megabytes | import java.io.*;
import java.awt.geom.Point2D;
import java.text.*;
import java.math.*;
import java.util.*;
public class Main implements Runnable {
final String filename = "";
int N;
boolean[][] ss;
public void solve() throws Exception {
N = iread();
int M = iread();
ss = new boolean[N][N];
for (int i = 0; i < M; i++) {
int x = iread(), y = iread();
x--;
y--;
ss[x][y] = true;
ss[y][x] = true;
}
out.write(smart() + "\n");
}
long smart() {
int[][] tt = new int[N][N];
int[] v = new int[N];
for (int a = 0; a < N; a++)
for (int b = a + 1; b < N; b++) {
if (ss[a][b]) {
v[a]++;
v[b]++;
}
for (int c = 0; c < N; c++)
if (ss[a][c] && ss[b][c])
tt[a][b]++;
tt[b][a] = tt[a][b];
}
long ans = 0;
for (int a = 0; a < N; a++)
for (int b = a + 1; b < N; b++) {
if (!ss[a][b])
continue;
for (int c = 0; c < N; c++) {
if (c == a)
continue;
if (c == b)
continue;
int k1 = tt[a][c];
if (ss[b][c])
k1--;
int k2 = tt[b][c];
if (ss[a][c])
k2--;
ans += k1 * k2;
}
for (int c = 0; c < N; c++)
if (ss[a][c] && ss[b][c])
ans -= (v[c] - 2);
}
// if (ans % 5 != 0)
// System.out.println("MEGAFAIL");
ans /= 5;
return ans;
}
long dummy() {
long ans = 0;
for (int a = 0; a < N; a++)
for (int b = 0; b < N; b++)
for (int c = 0; c < N; c++)
for (int d = 0; d < N; d++)
for (int e = 0; e < N; e++) {
if (a == b || a == c || a == d || a == e)
continue;
if (b == c || b == d || b == e)
continue;
if (c == e || c == d)
continue;
if (d == e)
continue;
if (ss[a][b] && ss[b][c] && ss[c][d] && ss[d][e]
&& ss[e][a])
ans++;
}
ans /= 10;
return ans;
}
void test() {
N = 15;
Random r = new Random(32167);
for (int k = 0;; k++) {
ss = new boolean[N][N];
for (int i = 0; i < N; i++)
for (int j = i + 1; j < N; j++) {
ss[i][j] = r.nextBoolean();
ss[j][i] = ss[i][j];
}
long ans1 = smart();
long ans2 = dummy();
if (ans1 != ans2) {
System.out.println("FAIL: smart=" + ans1 + " dummy=" + ans2);
break;
} else
System.out.println(k);
}
}
void test2() {
long t = System.currentTimeMillis();
N = 700;
ss = new boolean[N][N];
for (int i = 0; i < N; i++)
for (int j = i + 1; j < N; j++) {
ss[i][j] = true;
ss[j][i] = true;
}
long ans = smart();
System.out.println(ans);
System.out.println((System.currentTimeMillis() - t) + " ms");
}
public void run() {
try {
// test2();
in = new BufferedReader(new InputStreamReader(System.in));
out = new BufferedWriter(new OutputStreamWriter(System.out));
// in = new BufferedReader(new FileReader(filename+".in"));
// out = new BufferedWriter(new FileWriter(filename+".out"));
solve();
out.flush();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public int iread() throws Exception {
return Integer.parseInt(readword());
}
public double dread() throws Exception {
return Double.parseDouble(readword());
}
public long lread() throws Exception {
return Long.parseLong(readword());
}
BufferedReader in;
BufferedWriter out;
public String readword() throws IOException {
StringBuilder b = new StringBuilder();
int c;
c = in.read();
while (c >= 0 && c <= ' ')
c = in.read();
if (c < 0)
return "";
while (c > ' ') {
b.append((char) c);
c = in.read();
}
return b.toString();
}
public static void main(String[] args) {
try {
Locale.setDefault(Locale.US);
} catch (Exception e) {
}
new Thread(new Main()).start();
// new Thread(null, new Main(), "1", 1<<25).start();
}
}
| Java | ["5 5\n1 2\n2 3\n3 4\n4 5\n5 1", "5 10\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 10 seconds | ["1", "12"] | null | Java 6 | standard input | [
"combinatorics",
"graphs",
"matrices"
] | 74d9bb152295cb30315f6444906dd891 | The first line contains two integers n and m (1 ≤ n ≤ 700;0 ≤ m ≤ n·(n - 1) / 2), where n represents the number of junctions and m is the number of roads in the city. Then follow m lines containing the road descriptions, one in each line. Every road is set by a number of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi), where ai and bi represent the numbers of junctions, connected by the road. The junctions are numbered from 1 to n. It is not guaranteed that from any junction one can get to any other one moving along the roads. | 2,400 | Print the single number which represents the required number of ways. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | c9dcfe08697e62ec7c6b274e659e689e | train_004.jsonl | 1293552000 | According to the last order issued by the president of Berland every city of the country must have its own Ministry Defense building (their own Pentagon). A megapolis Berbourg was not an exception. This city has n junctions, some pairs of which are connected by two-way roads. Overall there are m roads in the city, no more than one between each pair of junctions.At the moment choosing a location place for Pentagon in Berbourg is being discussed. It has been decided that Pentagon should cover the territory of five different junctions which are joined into a cycle by roads. In the order to build Pentagon a special wall will be built along the roads (with high-tension razor, high-voltage wire and other attributes). Thus, the number of possible ways of building Pentagon in the city is equal to the number of different cycles at lengths of 5, composed of junctions and roads.Your task is to prints the number of ways of building Pentagon in Berbourg. Only well-optimized solutions will be accepted. Please, test your code on the maximal testcase. | 256 megabytes |
import java.io.*;
import java.util.*;
public class E{
long[]d;
void solve()throws Exception
{
int n = nextInt();
int m = nextInt();
boolean[][] g = new boolean[n][ n];
for (int i = 0; i < m; i++)
{
int a = nextInt() - 1;
int b = nextInt() - 1;
g[a][b] = g[b][a] = true;
}
long res = get(n, g);
System.out.println(res);
}
long get(int n, boolean[][] g)
{
long res = 0;
int[][] com = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++)
{
for (int k = 0; k < n; k++)
if (g[i][k] && g[j][k])
com[i][j]++;
com[j][i] = com[i][j];
}
int[][] have = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (g[i][j])
have[i][j] = 1;
int[] deg = new int[n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (g[i][j])
deg[i]++;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (g[i][j])
{
int add = 0;
for (int k = 0; k < n; k++)
if (k != i && k != j)
{
add += (com[i][k] - have[j][k]) * (com[j][k] - have[i][k]);
}
res += add;
}
long sub = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (g[i][j])
{
int cur = 0;
for (int k = 0; k < n; k++)
if (g[i][k] && g[k][j])
{
cur += (deg[k] - 2);
}
sub += cur;
}
res -= sub;
if (res % 5 != 0)
throw new AssertionError();
res /= 5;
return res;
}
BufferedReader reader;
PrintWriter writer;
StringTokenizer stk;
void run()throws Exception
{
reader=new BufferedReader(new InputStreamReader(System.in));
stk=null;
writer=new PrintWriter(System.out);
solve();
reader.close();
writer.close();
}
int nextInt()throws Exception
{
return Integer.parseInt(nextToken());
}
long nextLong()throws Exception
{
return Long.parseLong(nextToken());
}
double nextDouble()throws Exception
{
return Double.parseDouble(nextToken());
}
String nextString()throws Exception
{
return nextToken();
}
String nextLine()throws Exception
{
return reader.readLine();
}
String nextToken()throws Exception
{
if(stk==null || !stk.hasMoreTokens())
{
stk=new StringTokenizer(nextLine());
return nextToken();
}
return stk.nextToken();
}
public static void main(String[]a) throws Exception
{
new E().run();
}
} | Java | ["5 5\n1 2\n2 3\n3 4\n4 5\n5 1", "5 10\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 10 seconds | ["1", "12"] | null | Java 6 | standard input | [
"combinatorics",
"graphs",
"matrices"
] | 74d9bb152295cb30315f6444906dd891 | The first line contains two integers n and m (1 ≤ n ≤ 700;0 ≤ m ≤ n·(n - 1) / 2), where n represents the number of junctions and m is the number of roads in the city. Then follow m lines containing the road descriptions, one in each line. Every road is set by a number of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi), where ai and bi represent the numbers of junctions, connected by the road. The junctions are numbered from 1 to n. It is not guaranteed that from any junction one can get to any other one moving along the roads. | 2,400 | Print the single number which represents the required number of ways. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | 2f474dbc977b9b2779537dbaa8778124 | train_004.jsonl | 1293552000 | According to the last order issued by the president of Berland every city of the country must have its own Ministry Defense building (their own Pentagon). A megapolis Berbourg was not an exception. This city has n junctions, some pairs of which are connected by two-way roads. Overall there are m roads in the city, no more than one between each pair of junctions.At the moment choosing a location place for Pentagon in Berbourg is being discussed. It has been decided that Pentagon should cover the territory of five different junctions which are joined into a cycle by roads. In the order to build Pentagon a special wall will be built along the roads (with high-tension razor, high-voltage wire and other attributes). Thus, the number of possible ways of building Pentagon in the city is equal to the number of different cycles at lengths of 5, composed of junctions and roads.Your task is to prints the number of ways of building Pentagon in Berbourg. Only well-optimized solutions will be accepted. Please, test your code on the maximal testcase. | 256 megabytes |
import java.io.*;
import java.util.*;
public class E{
long[]d;
void solve()throws Exception
{
int n = nextInt();
int m = nextInt();
boolean[][] g = new boolean[n][ n];
for (int i = 0; i < m; i++)
{
int a = nextInt() - 1;
int b = nextInt() - 1;
g[a][b] = g[b][a] = true;
}
long res = get(n, g);
System.out.println(res);
}
long get(int n, boolean[][] g)
{
long res = 0;
int[][] com = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
if (g[i][k] && g[j][k])
com[i][j]++;
}
int[][] have = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (g[i][j])
have[i][j] = 1;
int[] deg = new int[n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (g[i][j])
deg[i]++;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (g[i][j])
{
int add = 0;
for (int k = 0; k < n; k++)
if (k != i && k != j)
{
add += (com[i][k] - have[j][k]) * (com[j][k] - have[i][k]);
}
res += add;
}
long sub = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (g[i][j])
{
int cur = 0;
for (int k = 0; k < n; k++)
if (g[i][k] && g[k][j])
{
cur += (deg[k] - 2);
}
sub += cur;
}
res -= sub;
if (res % 5 != 0)
throw new AssertionError();
res /= 5;
return res;
}
BufferedReader reader;
PrintWriter writer;
StringTokenizer stk;
void run()throws Exception
{
reader=new BufferedReader(new InputStreamReader(System.in));
stk=null;
writer=new PrintWriter(System.out);
solve();
reader.close();
writer.close();
}
int nextInt()throws Exception
{
return Integer.parseInt(nextToken());
}
long nextLong()throws Exception
{
return Long.parseLong(nextToken());
}
double nextDouble()throws Exception
{
return Double.parseDouble(nextToken());
}
String nextString()throws Exception
{
return nextToken();
}
String nextLine()throws Exception
{
return reader.readLine();
}
String nextToken()throws Exception
{
if(stk==null || !stk.hasMoreTokens())
{
stk=new StringTokenizer(nextLine());
return nextToken();
}
return stk.nextToken();
}
public static void main(String[]a) throws Exception
{
new E().run();
}
} | Java | ["5 5\n1 2\n2 3\n3 4\n4 5\n5 1", "5 10\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 10 seconds | ["1", "12"] | null | Java 6 | standard input | [
"combinatorics",
"graphs",
"matrices"
] | 74d9bb152295cb30315f6444906dd891 | The first line contains two integers n and m (1 ≤ n ≤ 700;0 ≤ m ≤ n·(n - 1) / 2), where n represents the number of junctions and m is the number of roads in the city. Then follow m lines containing the road descriptions, one in each line. Every road is set by a number of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi), where ai and bi represent the numbers of junctions, connected by the road. The junctions are numbered from 1 to n. It is not guaranteed that from any junction one can get to any other one moving along the roads. | 2,400 | Print the single number which represents the required number of ways. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | e9d0d4cbbc06ec25c46336b386ec5475 | train_004.jsonl | 1293552000 | According to the last order issued by the president of Berland every city of the country must have its own Ministry Defense building (their own Pentagon). A megapolis Berbourg was not an exception. This city has n junctions, some pairs of which are connected by two-way roads. Overall there are m roads in the city, no more than one between each pair of junctions.At the moment choosing a location place for Pentagon in Berbourg is being discussed. It has been decided that Pentagon should cover the territory of five different junctions which are joined into a cycle by roads. In the order to build Pentagon a special wall will be built along the roads (with high-tension razor, high-voltage wire and other attributes). Thus, the number of possible ways of building Pentagon in the city is equal to the number of different cycles at lengths of 5, composed of junctions and roads.Your task is to prints the number of ways of building Pentagon in Berbourg. Only well-optimized solutions will be accepted. Please, test your code on the maximal testcase. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.InputMismatchException;
/**
* @author Egor Kulikov (egor@egork.net)
*/
public class TaskE {
@SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
InputReader in;
PrintWriter out;
private static final int CELL = 20;
void solve() {
int n = in.readInt();
int m = in.readInt();
int[] deg = new int[n];
int[][] e = new int[n][(n + CELL - 1) / CELL];
boolean[][] g = new boolean[n][n];
for (int i = 0; i < m; i++) {
int a = in.readInt() - 1;
int b = in.readInt() - 1;
e[a][b / CELL] += 1 << (b % CELL);
e[b][a / CELL] += 1 << (a % CELL);
g[a][b] = g[b][a] = true;
deg[a]++;
deg[b]++;
}
int[] bitCount = new int[1 << CELL];
for (int i = 0; i < bitCount.length; i++)
bitCount[i] = bitCount[i >> 1] + (i & 1);
int[][] numPaths2 = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = 0; k < e[i].length; k++)
numPaths2[i][j] += bitCount[e[i][k] & e[j][k]];
numPaths2[j][i] = numPaths2[i][j];
}
}
long count = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (g[i][j]) {
for (int k = 0; k < n; k++) {
if (k != i && k != j)
count += numPaths2[i][k] * numPaths2[j][k];
}
}
}
}
for (int i = 0; i < n; i++) {
if (deg[i] <= 2)
continue;
for (int j = 0; j < n; j++) {
if (g[i][j]) {
for (int k = j + 1; k < n; k++) {
if (g[i][k] && g[j][k])
count -= 3 * (deg[i] - 2) + 1;
}
}
}
}
out.println(count / 5);
}
public static void main(String[] args) {
new TaskE().run();
}
TaskE() {
@SuppressWarnings({"UnusedDeclaration"})
String id = getClass().getName().toLowerCase();
//noinspection EmptyTryBlock
try {
// System.setIn(new FileInputStream(id + ".in"));
// System.setOut(new PrintStream(new FileOutputStream(id + ".out")));
// System.setIn(new FileInputStream("input.txt"));
// System.setOut(new PrintStream(new FileOutputStream("output.txt")));
} catch (Exception e) {
throw new RuntimeException(e);
}
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
void run() {
//noinspection InfiniteLoopStatement
solve();
exit();
}
@SuppressWarnings({"UnusedDeclaration"})
void exit() {
out.close();
System.exit(0);
}
@SuppressWarnings({"UnusedDeclaration"})
static class InputReader {
InputStream stream;
byte[] buf = new byte[1024];
int curChar, numChars;
InputReader(InputStream stream) {
this.stream = stream;
}
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++];
}
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;
}
long readLong() {
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;
}
String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
double readDouble() {
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, readInt());
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, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
}
}
| Java | ["5 5\n1 2\n2 3\n3 4\n4 5\n5 1", "5 10\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 10 seconds | ["1", "12"] | null | Java 6 | standard input | [
"combinatorics",
"graphs",
"matrices"
] | 74d9bb152295cb30315f6444906dd891 | The first line contains two integers n and m (1 ≤ n ≤ 700;0 ≤ m ≤ n·(n - 1) / 2), where n represents the number of junctions and m is the number of roads in the city. Then follow m lines containing the road descriptions, one in each line. Every road is set by a number of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi), where ai and bi represent the numbers of junctions, connected by the road. The junctions are numbered from 1 to n. It is not guaranteed that from any junction one can get to any other one moving along the roads. | 2,400 | Print the single number which represents the required number of ways. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | 73eb08789d6bb80d89afc27842f119dc | train_004.jsonl | 1293552000 | According to the last order issued by the president of Berland every city of the country must have its own Ministry Defense building (their own Pentagon). A megapolis Berbourg was not an exception. This city has n junctions, some pairs of which are connected by two-way roads. Overall there are m roads in the city, no more than one between each pair of junctions.At the moment choosing a location place for Pentagon in Berbourg is being discussed. It has been decided that Pentagon should cover the territory of five different junctions which are joined into a cycle by roads. In the order to build Pentagon a special wall will be built along the roads (with high-tension razor, high-voltage wire and other attributes). Thus, the number of possible ways of building Pentagon in the city is equal to the number of different cycles at lengths of 5, composed of junctions and roads.Your task is to prints the number of ways of building Pentagon in Berbourg. Only well-optimized solutions will be accepted. Please, test your code on the maximal testcase. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class E implements Runnable {
private void solve() throws IOException {
int n = nextInt(), m = nextInt();
boolean[][] c = new boolean[n][n];
int[] deg = new int[n];
for (int i = 0; i < m; ++i) {
int x = nextInt() - 1, y = nextInt() - 1;
c[x][y] = c[y][x] = true;
++deg[x];
++deg[y];
}
int[][] mid = new int[n][n];
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
for (int k = 0; k < n; ++k)
if (c[i][k] && c[k][j])
++mid[i][j];
long res = 0;
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j) {
if (!c[i][j])
continue;
for (int k = 0; k < n; ++k)
if (k != i && k != j)
res += (long) mid[i][k] * mid[j][k];
for (int k = 0; k < n; ++k)
if (k != i && k != j && c[k][j])
res -= mid[k][j];
for (int k = 0; k < n; ++k)
if (k != i && k != j && c[k][i])
res -= mid[k][i];
for (int k = 0; k < n; ++k)
if (k != i && k != j && c[k][j] && c[k][i]) {
res++;
res -= deg[k] - 2;
}
}
writer.print(res / 5);
}
public static void main(String[] args) {
new E().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
BigInteger nextBigInteger() throws IOException {
return new BigInteger(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
} | Java | ["5 5\n1 2\n2 3\n3 4\n4 5\n5 1", "5 10\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 10 seconds | ["1", "12"] | null | Java 6 | standard input | [
"combinatorics",
"graphs",
"matrices"
] | 74d9bb152295cb30315f6444906dd891 | The first line contains two integers n and m (1 ≤ n ≤ 700;0 ≤ m ≤ n·(n - 1) / 2), where n represents the number of junctions and m is the number of roads in the city. Then follow m lines containing the road descriptions, one in each line. Every road is set by a number of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi), where ai and bi represent the numbers of junctions, connected by the road. The junctions are numbered from 1 to n. It is not guaranteed that from any junction one can get to any other one moving along the roads. | 2,400 | Print the single number which represents the required number of ways. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | bc57cbbddcc943b049e82c0429b764f4 | train_004.jsonl | 1293552000 | According to the last order issued by the president of Berland every city of the country must have its own Ministry Defense building (their own Pentagon). A megapolis Berbourg was not an exception. This city has n junctions, some pairs of which are connected by two-way roads. Overall there are m roads in the city, no more than one between each pair of junctions.At the moment choosing a location place for Pentagon in Berbourg is being discussed. It has been decided that Pentagon should cover the territory of five different junctions which are joined into a cycle by roads. In the order to build Pentagon a special wall will be built along the roads (with high-tension razor, high-voltage wire and other attributes). Thus, the number of possible ways of building Pentagon in the city is equal to the number of different cycles at lengths of 5, composed of junctions and roads.Your task is to prints the number of ways of building Pentagon in Berbourg. Only well-optimized solutions will be accepted. Please, test your code on the maximal testcase. | 256 megabytes | import java.io.*;
import java.awt.geom.Point2D;
import java.text.*;
import java.math.*;
import java.util.*;
public class Main implements Runnable {
final String filename = "";
int N;
boolean[][] ss;
public void solve() throws Exception {
N = iread();
int M = iread();
ss = new boolean[N][N];
for (int i = 0; i < M; i++) {
int x = iread(), y = iread();
x--;
y--;
ss[x][y] = true;
ss[y][x] = true;
}
out.write(smart() + "\n");
}
long smart() {
int[][] tt = new int[N][N];
int[] v = new int[N];
for (int a = 0; a < N; a++)
for (int b = a + 1; b < N; b++) {
if (ss[a][b]) {
v[a]++;
v[b]++;
}
for (int c = 0; c < N; c++)
if (ss[a][c] && ss[b][c])
tt[a][b]++;
tt[b][a] = tt[a][b];
}
long ans = 0;
for (int a = 0; a < N; a++)
for (int b = a + 1; b < N; b++) {
if (!ss[a][b])
continue;
for (int c = 0; c < N; c++) {
if (c == a)
continue;
if (c == b)
continue;
int k1 = tt[a][c];
if (ss[b][c])
k1--;
int k2 = tt[b][c];
if (ss[a][c])
k2--;
ans += k1 * k2;
}
for (int c = 0; c < N; c++)
if (ss[a][c] && ss[b][c])
ans -= (v[c] - 2);
}
// if (ans % 5 != 0)
// System.out.println("MEGAFAIL");
ans /= 5;
return ans;
}
long dummy() {
long ans = 0;
for (int a = 0; a < N; a++)
for (int b = 0; b < N; b++)
for (int c = 0; c < N; c++)
for (int d = 0; d < N; d++)
for (int e = 0; e < N; e++) {
if (a == b || a == c || a == d || a == e)
continue;
if (b == c || b == d || b == e)
continue;
if (c == e || c == d)
continue;
if (d == e)
continue;
if (ss[a][b] && ss[b][c] && ss[c][d] && ss[d][e]
&& ss[e][a])
ans++;
}
ans /= 10;
return ans;
}
void test() {
N = 15;
Random r = new Random(32167);
for (int k = 0;; k++) {
ss = new boolean[N][N];
for (int i = 0; i < N; i++)
for (int j = i + 1; j < N; j++) {
ss[i][j] = r.nextBoolean();
ss[j][i] = ss[i][j];
}
long ans1 = smart();
long ans2 = dummy();
if (ans1 != ans2) {
System.out.println("FAIL: smart=" + ans1 + " dummy=" + ans2);
break;
} else
System.out.println(k);
}
}
void test2() {
long t = System.currentTimeMillis();
N = 700;
ss = new boolean[N][N];
for (int i = 0; i < N; i++)
for (int j = i + 1; j < N; j++) {
ss[i][j] = true;
ss[j][i] = true;
}
long ans = smart();
System.out.println(ans);
System.out.println((System.currentTimeMillis() - t) + " ms");
}
public void run() {
try {
// test2();
in = new BufferedReader(new InputStreamReader(System.in));
out = new BufferedWriter(new OutputStreamWriter(System.out));
// in = new BufferedReader(new FileReader(filename+".in"));
// out = new BufferedWriter(new FileWriter(filename+".out"));
solve();
out.flush();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public int iread() throws Exception {
return Integer.parseInt(readword());
}
public double dread() throws Exception {
return Double.parseDouble(readword());
}
public long lread() throws Exception {
return Long.parseLong(readword());
}
BufferedReader in;
BufferedWriter out;
public String readword() throws IOException {
StringBuilder b = new StringBuilder();
int c;
c = in.read();
while (c >= 0 && c <= ' ')
c = in.read();
if (c < 0)
return "";
while (c > ' ') {
b.append((char) c);
c = in.read();
}
return b.toString();
}
public static void main(String[] args) {
try {
Locale.setDefault(Locale.US);
} catch (Exception e) {
}
new Thread(new Main()).start();
// new Thread(null, new Main(), "1", 1<<25).start();
}
} | Java | ["5 5\n1 2\n2 3\n3 4\n4 5\n5 1", "5 10\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 10 seconds | ["1", "12"] | null | Java 6 | standard input | [
"combinatorics",
"graphs",
"matrices"
] | 74d9bb152295cb30315f6444906dd891 | The first line contains two integers n and m (1 ≤ n ≤ 700;0 ≤ m ≤ n·(n - 1) / 2), where n represents the number of junctions and m is the number of roads in the city. Then follow m lines containing the road descriptions, one in each line. Every road is set by a number of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi), where ai and bi represent the numbers of junctions, connected by the road. The junctions are numbered from 1 to n. It is not guaranteed that from any junction one can get to any other one moving along the roads. | 2,400 | Print the single number which represents the required number of ways. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | f68969814a210e3ae33f46089e6920c2 | train_004.jsonl | 1293552000 | According to the last order issued by the president of Berland every city of the country must have its own Ministry Defense building (their own Pentagon). A megapolis Berbourg was not an exception. This city has n junctions, some pairs of which are connected by two-way roads. Overall there are m roads in the city, no more than one between each pair of junctions.At the moment choosing a location place for Pentagon in Berbourg is being discussed. It has been decided that Pentagon should cover the territory of five different junctions which are joined into a cycle by roads. In the order to build Pentagon a special wall will be built along the roads (with high-tension razor, high-voltage wire and other attributes). Thus, the number of possible ways of building Pentagon in the city is equal to the number of different cycles at lengths of 5, composed of junctions and roads.Your task is to prints the number of ways of building Pentagon in Berbourg. Only well-optimized solutions will be accepted. Please, test your code on the maximal testcase. | 256 megabytes | //package round48;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
public class E10 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni();
long[][] M = new long[n][n];
for(int i = 0;i < m;i++){
int f = ni()-1,t = ni()-1;
M[f][t] = M[t][f] = 1;
}
long[][] M2 = p2(M);
long[][] M4 = p2(M2);
long[] diag5 = diag(M4, M);
long[] diag3 = diag(M2, M);
long tot = 0;
for(int i = 0;i < n;i++){
tot += diag5[i];
tot -= 5*diag3[i];
int d = -2;
for(int j = 0;j < n;j++){
d += M[i][j];
}
tot -= 5 * d * diag3[i];
}
// tr(tot);
out.println(tot / 10);
}
// long対称行列の2乗
public static long[][] p2(long[][] A)
{
int n = A.length;
long[][] C = new long[n][n];
for(int i = 0;i < n;i++){
for(int j = i;j < n;j++){
long sum = 0;
for(int k = 0;k < n;k++){
sum += A[i][k] * A[k][j];
}
C[i][j] = C[j][i] = (int)sum;
}
}
return C;
}
public static long[] diag(long[][] A, long[][] B)
{
int n = A[0].length;
long[] ret = new long[n];
for(int i = 0;i < n;i++){
long row = 0;
for(int k = 0;k < n;k++){
row += A[i][k] * B[k][i];
}
ret[i] = row;
}
return ret;
}
public static long[][] mul(long[][] A, long[][] B)
{
int m = A.length;
int n = A[0].length;
int o = B[0].length;
long[][] C = new long[m][o];
for(int i = 0;i < m;i++){
for(int j = 0;j < o;j++){
long sum = 0;
for(int k = 0;k < n;k++){
sum += A[i][k] * B[k][j];
}
C[i][j] = sum;
}
}
return C;
}
void run() throws Exception
{
// StringBuilder sb = new StringBuilder();
// sb.append(700 + " " + (700*699/2) + " ");
// int n = 700;
// for(int i = 1;i <= n;i++){
// for(int j = i+1;j <= n;j++){
// sb.append(i + " " + j + " ");
// }
// }
// INPUT = sb.toString();
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 E10().run();
}
public int ni()
{
try {
int num = 0;
boolean minus = false;
while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
if(num == '-'){
num = 0;
minus = true;
}else{
num -= '0';
}
while(true){
int b = is.read();
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
}
} catch (IOException e) {
}
return -1;
}
public long nl()
{
try {
long num = 0;
boolean minus = false;
while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
if(num == '-'){
num = 0;
minus = true;
}else{
num -= '0';
}
while(true){
int b = is.read();
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
}
} catch (IOException e) {
}
return -1;
}
public String ns()
{
try{
int b = 0;
StringBuilder sb = new StringBuilder();
while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' '));
if(b == -1)return "";
sb.append((char)b);
while(true){
b = is.read();
if(b == -1)return sb.toString();
if(b == '\r' || b == '\n' || b == ' ')return sb.toString();
sb.append((char)b);
}
} catch (IOException e) {
}
return "";
}
public char[] ns(int n)
{
char[] buf = new char[n];
try{
int b = 0, p = 0;
while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n'));
if(b == -1)return null;
buf[p++] = (char)b;
while(p < n){
b = is.read();
if(b == -1 || b == ' ' || b == '\r' || b == '\n')break;
buf[p++] = (char)b;
}
return Arrays.copyOf(buf, p);
} catch (IOException e) {
}
return null;
}
double nd() { return Double.parseDouble(ns()); }
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["5 5\n1 2\n2 3\n3 4\n4 5\n5 1", "5 10\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 10 seconds | ["1", "12"] | null | Java 6 | standard input | [
"combinatorics",
"graphs",
"matrices"
] | 74d9bb152295cb30315f6444906dd891 | The first line contains two integers n and m (1 ≤ n ≤ 700;0 ≤ m ≤ n·(n - 1) / 2), where n represents the number of junctions and m is the number of roads in the city. Then follow m lines containing the road descriptions, one in each line. Every road is set by a number of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi), where ai and bi represent the numbers of junctions, connected by the road. The junctions are numbered from 1 to n. It is not guaranteed that from any junction one can get to any other one moving along the roads. | 2,400 | Print the single number which represents the required number of ways. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | c821dd51ce6f3c961888cc89864eaaed | train_004.jsonl | 1293552000 | According to the last order issued by the president of Berland every city of the country must have its own Ministry Defense building (their own Pentagon). A megapolis Berbourg was not an exception. This city has n junctions, some pairs of which are connected by two-way roads. Overall there are m roads in the city, no more than one between each pair of junctions.At the moment choosing a location place for Pentagon in Berbourg is being discussed. It has been decided that Pentagon should cover the territory of five different junctions which are joined into a cycle by roads. In the order to build Pentagon a special wall will be built along the roads (with high-tension razor, high-voltage wire and other attributes). Thus, the number of possible ways of building Pentagon in the city is equal to the number of different cycles at lengths of 5, composed of junctions and roads.Your task is to prints the number of ways of building Pentagon in Berbourg. Only well-optimized solutions will be accepted. Please, test your code on the maximal testcase. | 256 megabytes | import java.io.*;
import java.util.*;
public class E {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long m = sc.nextLong();
long[][] adj = new long[n][n];
long[][] adj2 = new long[n][n];
long[][] adj3 = new long[n][n];
long[][] adj5 = new long[n][n];
for (int i=0; i<m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
adj[a-1][b-1] = adj[b-1][a-1] = 1;
}
mul(adj, adj, adj2);
mul(adj2, adj, adj3);
mul(adj2, adj3, adj5);
/*
print(adj);
System.out.println("2:");
print(adj2);
System.out.println("3:");
print(adj3);
System.out.println("5:");
print(adj5);
*/
long sum = 0;
for (int i=0; i<n; i++) {
sum += adj5[i][i]; // to yourself in 5 steps
sum -= adj3[i][i] * adj2[i][i] * 2;
for (int j=0; j<n; j++) {
if (adj[i][j] > 0) {
sum -= adj3[j][j]; // A->B->C->D->B->A
sum -= adj2[j][j] * adj2[j][i] * 2; // A->B->C->B->D->A
sum += adj2[j][i] * 5;
}
}
}
//System.out.format("sum=%d sum/10=%d\n", sum, sum/10);
System.out.println(sum/10);
}
public static void mul(long[][] a, long[][] b, long[][] res) {
int len = a.length;
for (int i=0; i<len; i++) {
for (int j=0; j<=i; j++) {
long sum = 0;
for (int k=0; k<len; k++) {
sum += a[i][k] * b[k][j];
}
res[i][j] = res[j][i] = sum;
}
}
}
public static void print(long[][] a) {
int len = a.length;
for (int i=0; i<len; i++) {
for (int j=0; j<len; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
| Java | ["5 5\n1 2\n2 3\n3 4\n4 5\n5 1", "5 10\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5"] | 10 seconds | ["1", "12"] | null | Java 6 | standard input | [
"combinatorics",
"graphs",
"matrices"
] | 74d9bb152295cb30315f6444906dd891 | The first line contains two integers n and m (1 ≤ n ≤ 700;0 ≤ m ≤ n·(n - 1) / 2), where n represents the number of junctions and m is the number of roads in the city. Then follow m lines containing the road descriptions, one in each line. Every road is set by a number of integers ai, bi (1 ≤ ai, bi ≤ n;ai ≠ bi), where ai and bi represent the numbers of junctions, connected by the road. The junctions are numbered from 1 to n. It is not guaranteed that from any junction one can get to any other one moving along the roads. | 2,400 | Print the single number which represents the required number of ways. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d). | standard output | |
PASSED | b665061dbf3c33adc9b11f672278780e | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=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')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void main(String args[]) throws IOException {
Scan input=new Scan();
int test=input.scanInt();
StringBuilder ans=new StringBuilder("");
for(int t=1;t<=test;t++) {
int n=input.scanInt();
long arr[]=new long[n];
for(int i=0;i<n;i++) {
arr[i]=input.scanInt();
}
if(solve(n,arr)) {
ans.append("YES\n");
}
else {
ans.append("NO\n");
}
}
System.out.println(ans);
}
public static boolean solve(int n,long arr[]) {
long total=0;
for(int i=0;i<n;i++) {
total+=arr[i];
}
long sum=0;
for(int i=0;i<n-1;i++) {
sum+=arr[i];
if(sum>=total) {
return false;
}
if(sum<0) {
sum=0;
}
}
sum=0;
for(int i=1;i<n;i++) {
sum+=arr[i];
if(sum>=total) {
return false;
}
if(sum<0) {
sum=0;
}
}
return true;
}
}
| Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | 3014a8ca720f885f38f04c93fe12de83 | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | import java.util.*;
public class cupcakes {
private static boolean posprefix(int[] a) {
long sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
if (sum <= 0) { return false; }
}
sum = 0;
for (int i = a.length - 1; i >= 0; i--) {
sum += a[i];
if (sum <= 0) { return false; }
}
return true;
}
public static void main(String[] args) {
Scanner iangay = new Scanner(System.in);
int tc = iangay.nextInt();
while (tc --> 0) {
int length = iangay.nextInt();
int[] cupcakes = new int[length];
for (int i = 0; i < length; i++) { cupcakes[i] = iangay.nextInt(); }
if (posprefix(cupcakes)) { System.out.println("YES"); }
else { System.out.println("NO"); }
}
}
} | Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | 3a80f9b230b2e68f2e1008f3c638a4cc | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | import java.io.*;
import java.util.*;
public class temp1 {
public static PrintWriter out;
static int o = 0, e = 0;
static int[] par;
static int[][][][] dp;
static ArrayList<Integer>[] a;
static int ans = 0;
public static void main(String[] args) throws IOException {
// Scanner scn = new Scanner(System.in);
Reader scn = new Reader();
int t = scn.nextInt();
while (t-- != 0) {
int n = scn.nextInt();
long[] a = scn.nextLongArray(n);
long sum = 0;
for (long i : a)
sum += i;
long cur = a[0], tot = a[0];
for (int i = 1; i < n - 1; i++) {
if (cur > 0)
cur += a[i];
else
cur = a[i];
tot = Math.max(tot, cur);
}
cur = a[1];
long tot1 = a[1];
for (int i = 2; i < n; i++) {
if (cur > 0)
cur += a[i];
else
cur = a[i];
tot1 = Math.max(tot1, cur);
}
tot = Math.max(tot, tot1);
if (sum > tot)
System.out.println("YES");
else
System.out.println("NO");
}
}
// _________________________TEMPLATE_____________________________________________________________
// private static int gcd(int a, int b) {
// if(a== 0)
// return b;
//
// return gcd(b%a,a);
// }
// static class comp implements Comparator<pair> {
//
// @Override
// public int compare(pair o1, pair o2) {
//
// return (int) (o1.y - o1.y);
// }
//
// }
static class pair implements Comparable<pair> {
long x = 0;
long y = 0;
pair(long a, long s) {
x = Math.min(a, s);
y = Math.max(a, s);
}
@Override
public int compareTo(pair o) {
if (this.x != o.x)
return (int) (o.x - this.x);
else
return (int) (o.y - this.y);
}
}
public 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[100000 + 1]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public int[][] nextInt2DArray(int m, int n) throws IOException {
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
arr[i][j] = nextInt();
}
return arr;
}
}
} | Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | 71cf4c64e526085f21a98a51653d2a0d | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
for(int k = 0; k < n; k++){
boolean z = false;
int a = scn.nextInt();
int[] b = new int[a];
for(int i = 0; i < a; i++){
b[i] = scn.nextInt();
}
long s = 0;
for(int i = 0; i < a; i++){
s += b[i];
if(s <= 0){
System.out.println("NO");
z = true;
break;
}
}
if(z == true) continue;
s = 0;
for(int i = a - 1; i >= 0; i--){
s += b[i];
if(s <= 0){
System.out.println("NO");
z = true;
break;
}
}
if(z == true) continue;
System.out.println("YES");
}
}
} | Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | 762f272335f6550db869faf945840d4c | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | 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 void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int tc=sc.nextInt();
for(int i=0;i<tc;i++)
{
int len =sc.nextInt();
Long arr[]=new Long[len];
Long totalsum=0L;
for(int j=0;j<len;j++)
{ Long tem=sc.nextLong();
totalsum =totalsum+tem;
arr[j]=tem;
}
Long max=0L;
Long cur=0L;
for(int k=0;k<len-1;k++)
{
cur=cur+arr[k];
if(cur<0)
{
cur=0L;
}else if(cur>max)
{
max=cur;
}
}
Long max1=0L;
Long cur1=0L;
for(int m=len-1;m>=1;m--)
{
cur1=cur1+arr[m];
if(cur1<0)
{
cur1=0L;
}else if(cur1>max1)
{
max1=cur1;
}
}
// System.out.println(max1);
Long max3=Math.max(max,max1);
// System.out.println(max3);
if(totalsum>max3)
{
System.out.println("YES");
}else
{
System.out.println("NO");
}
}
}
}
| Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | a0fc0d7c4c2b436d65e14b04131a3ded | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | import java.util.Scanner;
public class JustEatIt {
static int t,n;
static int[] a;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
t=sc.nextInt();
for(int j=t; j>0;j--){
n=sc.nextInt();
a= new int[n];
for(int i=0; i<n; i++){
a[i]=sc.nextInt();
}
if(solve()){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
public static boolean solve(){
long sum=0;
for(int i=0; i<n; i++){
sum += a[i];
if(sum<=0){return false;}
}
sum=0;
for(int i=n-1; i>=0; i--){
sum+=a[i];
if(sum<=0){ return false;}
}
return true;
}
}
| Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | 3f049b0a0207e2aeeccc872ceaef6b8a | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
for (int i = 0; i < t; i++) {
boolean fin = false;
int n = scan.nextInt();
long[] arr = new long[n + 1];
for (int j = 1; j < n + 1; j++)
arr[j] = scan.nextInt();
long[] preSum = new long[n + 1]; // prefix sum
for (int j = 0; j < n; j++) {
preSum[j + 1] = preSum[j] + arr[j + 1];
if (preSum[j + 1] < 1) {
System.out.println("NO");
fin = true;
break;
}
}
if (fin) continue;
long[] sufSum = new long[n + 2]; // suffix sum
for (int j = n + 1; j > 0; j--) {
sufSum[j - 1] = sufSum[j] + arr[j - 1];
if (sufSum[j - 1] < 1) {
System.out.println("NO");
fin = true;
break;
}
}
if (!fin) System.out.println("YES");
}
}
}
| Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | c4dd10d76a6b8e3318284d8ccc913dde | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | import java.util.*;
import java.io.*;
public class B613
{
static boolean changed;
public static void main(String [] args)
{
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int t = sc.nextInt();
for (int i = 0; i <t; i++)
{
int n = sc.nextInt();
int [] arr = new int [n];
for (int k = 0; k < n; k++)
{
arr[k] = sc.nextInt();
}
long [] prefix = new long [n];
prefix[0] = arr[0];
changed = false;
for (int k = 1; k < n; k++)
{
prefix[k] = prefix[k-1] + arr[k];
}
if (maxDiff(prefix, n) <= prefix[n-1] && !changed)
{
out.println("YES");
}
else
{
out.println("NO");
}
}
out.close();
}
//-----------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;
}
}
static long maxDiff(long arr[], int arr_size)
{
// Maximum difference found so far
long max_diff = arr[arr_size - 1];
// Minimum number visited so far
long min_element = 0;
for(int i = 0; i < arr_size; i++)
{
if (arr[i] - min_element >= max_diff)
{
max_diff = arr[i] - min_element;
if (i != arr_size - 1)
{
changed = true;
}
}
if (arr[i] <= min_element)
{
min_element = arr[i];
if (i != 0)
{
changed = true;
}
}
}
return max_diff;
}
} | Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | bdfa347f9007677cc4484e9bfb766af3 | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Reader input = new Reader();
PrintWriter out = new PrintWriter(System.out);
int t = input.nextInt();
for (int i = 0; i < t; i++) {
int n = input.nextInt();
long[] arg = new long[n];
long sum = 0;
boolean answer = true;
for (int j = 0; j < n; j++) {
arg[j] = input.nextLong();
sum += arg[j];
}
long tmpSum = 0;
int start = 0, end;
for (int j = 0; j < n; j++) {
tmpSum += arg[j];
end = j;
if (tmpSum >= sum) {
if (!(start == 0 && end == n - 1)) {
answer = false;
break;
}
}
if (tmpSum <= 0) {
tmpSum = 0;
start = j;
while (j + 1 < n) {
if (arg[j + 1] > 0) {
start = j + 1;
break;
} else j++;
}
}
}
if (sum <= 0)
answer = false;
if (answer) {
out.println("YES");
} else {
out.println("NO");
}
}
out.close();
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
}
| Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | 041a4f4d09c1c4e277d3cb083ab73fec | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution1285B {
public static void main(String[] args) {
FastReader fr = new FastReader();
int t = fr.nextInt();
while (t-- > 0)
{
int n = fr.nextInt();
String[] parts = fr.nextLine().trim().split(" ");
int[] cupcakes = new int[n];
for (int i = 0; i < n; ++i) {
cupcakes[i] = Integer.parseInt(parts[i]);
}
if (isEat(cupcakes)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
private static boolean isEat(int[] cupcakes) {
long sum = 0;
for (int i = 0; i < cupcakes.length; ++i) {
sum += cupcakes[i];
if (sum <= 0) return false;
}
sum = 0;
for (int i = cupcakes.length - 1; i >= 0; i--)
{
sum += cupcakes[i];
if (sum <= 0) return false;
}
return true;
}
public static class FastReader {
private BufferedReader br;
private StringTokenizer st;
public FastReader() {
this.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 | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | 4b42821f5f8879ac1c4a332f004a71ff | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | import java.util.Scanner;
import java.lang.Math;
public class Main {
public static final int Max = 100100;
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int T,n;
long sum;
int[] number= new int[Max];
long[] dp1=new long[Max];
long[] dp2=new long[Max];
T=in.nextInt();
for(int i=1;i<=T;i++){
n=in.nextInt();
sum=0;
for(int j=1;j<=n;j++){
number[j]=in.nextInt();
sum+=number[j];
dp1[j]=dp2[j]=-Max*Max;
}
dp1[1]=number[1];
dp2[2]=number[2];
for(int j=2;j<n;j++){
dp1[j]=Math.max(dp1[j-1]+number[j],number[j]);
}
for(int j=3;j<=n;j++){
dp2[j]=Math.max(dp2[j-1]+number[j],number[j]);
}
long sum2=-Max*Max;
for(int j=1;j<=n;j++){
sum2=Math.max(sum2,Math.max(dp1[j],dp2[j]));
}
if(sum2<sum){
System.out.println("YES");
}else {
System.out.println("NO");
}
}
}
}
| Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | 652a9555807b78b86be08c34fcd23cd3 | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | // package com.company;
import java.io.*;
import java.util.*;
/*
*@author jigar_nainuji
*/
public class Main {
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int tc = Integer.parseInt(br.readLine());
while(tc-->0)
{
int n = Integer.parseInt(br.readLine());
long sum=0;
String b[] = br.readLine().split(" ");
long max_so_far = Integer.MIN_VALUE,max_ending_here = 0,start = 0,
end = 0, s = 0;
for (int i = 0; i < n; i++)
{
max_ending_here +=Integer.parseInt(b[i]);
sum+=Integer.parseInt(b[i]);
if (max_so_far < max_ending_here)
{
max_so_far = max_ending_here;
start = s;
end = i;
}
if (max_ending_here < 0)
{
max_ending_here = 0;
s = i + 1;
}
}
// System.out.println(max_so_far+" "+sum+" "+start+" "+end);
if(max_so_far == sum && start==0 && end==n-1)
{
long max_so_far1 = Integer.MIN_VALUE,max_ending_here1 = 0,start1 = 0,
end1 = 0, s1 = 0;
for (int i = 0; i < n; i++)
{
max_ending_here1 +=Integer.parseInt(b[i]);
if (max_so_far1 <= max_ending_here1)
{
max_so_far1 = max_ending_here1;
start1 = s1;
end1 = i;
}
if (max_ending_here1 <= 0)
{
max_ending_here1 = 0;
s1 = i + 1;
}
}
if(max_so_far1 == sum && start1==0 && end1==n-1) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
else if(max_so_far < sum)
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}
} | Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | c656aa415b407b34c84c5936e2e476ff | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | import java.util.*;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.*;
public class bachao
{
public static void main(String args[])throws IOException
{
//FastReader in=new fastReader(System.in);
Scanner in=new Scanner(System.in);
int t=in.nextInt(),i,j;
while(t-->0) {
int n=in.nextInt();
int a[] = new int[n];
long sum=0,max1=0,max2=0,x;
for(i=0;i<n;i++) {
a[i]=in.nextInt();
sum+=a[i];
}
x=0;
for(i=0;i<n-1;i++) {
x=x+a[i];
if(max1<x)
max1=x;
if(x<0)
x=0;
}
//System.out.print(max1+" ");
x=0;
for(i=1;i<n;i++) {
x=x+a[i];
if(max2<x)
max2=x;
if(x<0)
x=0;
}
//System.out.println(max2);
if(Math.max(max1,max2)>=sum)
System.out.println("NO");
else
System.out.println("YES");
}
}
}
/*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();
}
String nextLine() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
StringBuilder sb = new StringBuilder();
for (; c != 10 && c != 13; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
char nextChar() throws IOException {
int c;
for (c = scan(); c <= 32; c = scan()) ;
return (char) c;
}
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 | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | 0f9652f2510da18ce2082cffe4682351 | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | //package CodeforcesProject;
import java.io.*;
import java.lang.*;
import java.util.*;
import java.util.function.BiFunction;
public class Main extends IO {
public static void main(String[] args) throws Exception {
int count = readInt();
for (int i = 0; i < count; i++) {
int quantity = readInt();
int[] base = readArrayInt(" ");
long result = 0;
long ans = 0;
long maxResult = 0;
boolean check = false;
boolean exit = false;
for (int j = 0; j < quantity; j++) {
ans += base[j];
if (j + 1 < quantity) {
if (base[j] < 0) {
maxResult = Math.max(maxResult, result);
exit = true;
}
result += base[j];
if (result > maxResult){
exit = false;
}
} else {
if (base[j] < 0) {
check = true;
} else {
result += base[j];
}
}
if (result <= 0) {
check = true;
result = 0;
}
}
if (maxResult > result || (maxResult == result && exit)) {
result = maxResult;
} else if (!check) {
result -= Math.min(base[0], base[quantity - 1]);
}
writeString(ans > result ? "YES" : "NO", "\n");
}
print();
}
}
class math {
protected static int remains = 0x989687;
protected static int gcd(int a, int b) { // NOD
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
protected static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
protected static float gcd(float a, float b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
protected static double gcd(double a, double b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
protected static double lcm(double a, double b) { // NOK
return a / gcd(a, b) * b;
}
protected static float lcm(float a, float b) { // NOK
return a / gcd(a, b) * b;
}
protected static int lcm(int a, int b) { // NOK
return a / gcd(a, b) * b;
}
protected static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
protected static double log(double value, int base) {
return Math.log(value) / Math.log(base);
}
protected static long factorial(int number) {
if (number < 0) {
return 0;
}
return solveFactorial(number);
}
private static long solveFactorial(int number) {
if (number > 0) {
return solveFactorial(number - 1) * number;
}
return 1;
}
}
class Int implements Comparable<Integer> {
protected int value;
Int(int value) {
this.value = value;
}
@Override
public int compareTo(Integer o) {
return (this.value < o) ? -1 : ((this.value == o) ? 0 : 1);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == (Integer) obj;
}
return false;
}
@Override
public int hashCode() {
return value;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
}
class Fraction<T extends Number> extends Pair {
private Fraction(T dividend, T divider) {
super(dividend, divider);
reduce();
}
protected static <T extends Number> Fraction<T> createFraction(T dividend, T divider) {
return new Fraction<>(dividend, divider);
}
protected void reduce() {
if (getFirstElement() instanceof Integer) {
Integer Dividend = (Integer) getFirstElement();
Integer Divider = (Integer) getSecondElement();
int gcd = math.gcd(Dividend, Divider);
setFirst(Dividend / gcd);
setSecond(Divider / gcd);
} else if (getFirstElement() instanceof Long) {
Long Dividend = (Long) getFirstElement();
Long Divider = (Long) getSecondElement();
long gcd = math.gcd(Dividend, Divider);
setFirst(Dividend / gcd);
setSecond(Divider / gcd);
} else if (getFirstElement() instanceof Float) {
Float Dividend = (Float) getFirstElement();
Float Divider = (Float) getSecondElement();
float gcd = math.gcd(Dividend, Divider);
setFirst(Dividend / gcd);
setSecond(Divider / gcd);
} else if (getFirstElement() instanceof Double) {
Double Dividend = (Double) getFirstElement();
Double Divider = (Double) getSecondElement();
double gcd = math.gcd(Dividend, Divider);
setFirst(Dividend / gcd);
setSecond(Divider / gcd);
}
}
protected void addWithoutReturn(Fraction number) throws UnsupportedOperationException {
add(number, 0);
}
private Fraction add(Fraction number, int function) throws UnsupportedOperationException {
if (getFirstElement() instanceof Integer && number.getFirstElement() instanceof Integer) {
Integer Dividend = (Integer) getFirstElement();
Integer Divider = (Integer) getSecondElement();
Integer Dividend1 = (Integer) number.getFirstElement();
Integer Divider1 = (Integer) number.getSecondElement();
Integer lcm = math.lcm(Divider, Divider1);
if (function == 0) {
setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1);
setSecond(lcm);
reduce();
return null;
}
Fraction result = Fraction.createFraction((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm);
result.reduce();
return result;
} else if (getFirstElement() instanceof Long && number.getFirstElement() instanceof Long) {
Long Dividend = (Long) getFirstElement();
Long Divider = (Long) getSecondElement();
Long Dividend1 = (Long) number.getFirstElement();
Long Divider1 = (Long) number.getSecondElement();
Long lcm = math.lcm(Divider, Divider1);
if (function == 0) {
setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1);
setSecond(lcm);
reduce();
return null;
}
Fraction result = Fraction.createFraction((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm);
result.reduce();
return result;
} else if (getFirstElement() instanceof Float && number.getFirstElement() instanceof Float) {
Float Dividend = (Float) getFirstElement();
Float Divider = (Float) getSecondElement();
Float Dividend1 = (Float) number.getFirstElement();
Float Divider1 = (Float) number.getSecondElement();
Float lcm = math.lcm(Divider, Divider1);
if (function == 0) {
setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1);
setSecond(lcm);
reduce();
return null;
}
Fraction result = Fraction.createFraction((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm);
result.reduce();
return result;
} else if (getFirstElement() instanceof Double && number.getFirstElement() instanceof Double) {
Double Dividend = (Double) getFirstElement();
Double Divider = (Double) getSecondElement();
Double Dividend1 = (Double) number.getFirstElement();
Double Divider1 = (Double) number.getSecondElement();
Double lcm = math.lcm(Divider, Divider1);
if (function == 0) {
setFirst((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1);
setSecond(lcm);
reduce();
return null;
}
Fraction result = Fraction.createFraction((lcm / Divider) * Dividend + (lcm / Divider1) * Dividend1, lcm);
result.reduce();
return result;
} else {
throw new UnsupportedOperationException();
}
}
protected Fraction addWithReturn(Fraction number) {
return add(number, 1);
}
protected void multiplyWithoutReturn(Fraction number) throws UnsupportedOperationException {
multiply(number, 0);
}
protected Fraction multiplyWithReturn(Fraction number) throws UnsupportedOperationException {
return multiply(number, 1);
}
private Fraction multiply(Fraction number, int function) throws UnsupportedOperationException {
if (getFirstElement() instanceof Integer && number.getFirstElement() instanceof Integer) {
Integer first = (Integer) getFirstElement() * (Integer) number.getFirstElement();
Integer second = (Integer) getSecondElement() * (Integer) number.getSecondElement();
if (function == 0) {
setFirst(first);
setSecond(second);
reduce();
return null;
}
Fraction answer = Fraction.createFraction(first, second);
answer.reduce();
return answer;
} else if (getFirstElement() instanceof Long && number.getFirstElement() instanceof Long) {
Long first = (Long) getFirstElement() * (Long) number.getFirstElement();
Long second = (Long) getSecondElement() * (Long) number.getSecondElement();
if (function == 0) {
setFirst(first);
setSecond(second);
reduce();
return null;
}
Fraction answer = Fraction.createFraction(first, second);
answer.reduce();
return answer;
} else if (getFirstElement() instanceof Float && number.getFirstElement() instanceof Float) {
Float first = (Float) getFirstElement() * (Float) number.getFirstElement();
Float second = (Float) getSecondElement() * (Float) number.getSecondElement();
if (function == 0) {
setFirst(first);
setSecond(second);
reduce();
return null;
}
Fraction answer = Fraction.createFraction(first, second);
answer.reduce();
return answer;
} else if (getFirstElement() instanceof Double && number.getFirstElement() instanceof Double) {
Double first = (Double) getFirstElement() * (Double) number.getFirstElement();
Double second = (Double) getSecondElement() * (Double) number.getSecondElement();
if (function == 0) {
setFirst(first);
setSecond(second);
reduce();
return null;
}
Fraction answer = Fraction.createFraction(first, second);
answer.reduce();
return answer;
} else {
throw new UnsupportedOperationException();
}
}
}
class Pair<T, T1> implements Cloneable {
private T first;
private T1 second;
Pair(T obj, T1 obj1) {
first = obj;
second = obj1;
}
protected static <T, T1> Pair<T, T1> createPair(T element, T1 element1) {
return new Pair<>(element, element1);
}
protected T getFirstElement() {
return first;
}
protected T1 getSecondElement() {
return second;
}
protected void setFirst(T element) {
first = element;
}
protected void setSecond(T1 element) {
second = element;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Pair)) {
return false;
}
Pair pair = (Pair) obj;
return first.equals(pair.first) && second.equals(pair.second);
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + (first == null ? 0 : first.hashCode());
return 31 * hashCode + (second == null ? 0 : second.hashCode());
}
@Override
public Object clone() {
return Pair.createPair(first, second);
}
}
class Graph {
private int[][] base;
private boolean[] used;
private int quantity;
private Integer[] ancestor;
public int[][] getBase() {
return base.clone();
}
public boolean[] getUsed() {
return used.clone();
}
public int getQuantity() {
return quantity;
}
public Integer[] getAncestor() {
return ancestor.clone();
}
public void setBase(int[][] base) {
this.base = base;
}
protected void start(int length) {
used = new boolean[length];
ancestor = new Integer[length];
Arrays.fill(ancestor, -1);
quantity = 0;
}
protected void edgesMatrixToDefault(int length, int quantity, boolean readConsole, int[][] value) throws Exception {
base = new int[length][];
List<ArrayList<Integer>> inputBase = new ArrayList<>();
for (int i = 0; i < length; i++) {
inputBase.add(new ArrayList<>());
}
for (int i = 0; i < quantity; i++) {
int[] input = readConsole ? IO.readArrayInt(" ") : value[i];
inputBase.get(input[0] - 1).add(input[1] - 1);
//inputBase.get(input[0] - 1).add(input[2]); // price
inputBase.get(input[1] - 1).add(input[0] - 1);
//inputBase.get(input[1] - 1).add(input[2]); // price
}
for (int i = 0; i < length; i++) {
base[i] = inputBase.get(i).stream().mapToInt(Integer::intValue).toArray();
}
start(length);
}
protected void adjacencyMatrixToDefault(int length, int not, boolean readConsole, int[][] value) throws Exception {
this.base = new int[length][];
List<Integer> buffer = new ArrayList<>();
for (int i = 0; i < length; i++) {
int[] InputArray = readConsole ? IO.readArrayInt(" ") : value[i];
for (int index = 0; index < length; index++) {
if (i != index && InputArray[index] != not) {
buffer.add(index);
// buffer.add(InputArray[index]); // price
}
}
this.base[i] = buffer.stream().mapToInt(Integer::intValue).toArray();
buffer.clear();
}
start(length);
}
protected void dfs(int position) throws Exception {
used[position] = true;
quantity++;
int next;
for (int index = 0; index < base[position].length; index++) {
next = base[position][index];
if (!used[next]) {
ancestor[next] = position;
dfs(next);
} /*else {
if (next != ancestor[position]) { // if cycle
throw new Exception();
}
}*/
}
}
protected int dijkstra(int start, int stop, int size) {
start--;
stop--;
int[] dist = new int[size];
for (int i = 0; i < size; i++) {
if (i != start) {
dist[i] = Integer.MAX_VALUE;
}
ancestor[i] = start;
}
Queue<int[]> queue = new PriorityQueue<>(Comparator.comparingInt((int[] ints) -> ints[1]));
queue.add(new int[]{start, 0});
int position;
int[] getQueue;
while (queue.size() != 0) {
getQueue = queue.poll();
position = getQueue[0];
if (getQueue[1] > dist[position]) {
continue;
}
for (int index = 0; index < this.base[position].length; index += 2) {
if (dist[position] + this.base[position][index + 1] < dist[this.base[position][index]] && !this.used[this.base[position][index]]) {
dist[this.base[position][index]] = dist[position] + this.base[position][index + 1];
this.ancestor[this.base[position][index]] = position;
queue.add(new int[]{this.base[position][index], dist[this.base[position][index]]});
}
}
used[position] = true;
}
return dist[stop] == Integer.MAX_VALUE ? -1 : dist[stop];
}
protected static boolean solveFloydWarshall(int[][] base, int length, int not) {
for (int k = 0; k < length; k++) {
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
if (base[i][k] == not || base[k][j] == not) {
continue;
}
int total = base[i][k] + base[k][j];
if (base[i][j] != not) {
base[i][j] = Math.min(base[i][j], total);
} else {
base[i][j] = total;
}
}
}
}
for (int index = 0; index < length; index++) {
if (base[index][index] != 0) { // if cycle
return false;
}
}
return true;
}
protected static Pair<Long, int[][]> solveKruskal(int[][] edgesMatrix, final int countVertex, final int indexSort) {
int[][] answer = new int[countVertex - 1][2];
long sum = 0;
Arrays.sort(edgesMatrix, Comparator.comparingInt(value -> value[indexSort]));
SystemOfDisjointSets dsu = new SystemOfDisjointSets(countVertex);
for (int i = 0; i < countVertex; i++) {
dsu.makeSet(i);
}
int index = 0;
for (int[] value : edgesMatrix) {
if (dsu.mergeSets(value[0], value[1])) {
sum += value[indexSort];
answer[index] = new int[]{value[0], value[1]};
index++;
}
}
if (index < countVertex - 1) {
return Pair.createPair(null, null);
}
return Pair.createPair(sum, answer);
}
static class SegmentTree {
private int[] segmentArray;
private BiFunction<Integer, Integer, Integer> function;
protected void setSegmentArray(int[] segmentArray) {
this.segmentArray = segmentArray;
}
protected int[] getSegmentArray() {
return segmentArray.clone();
}
protected void setFunction(BiFunction<Integer, Integer, Integer> function) {
this.function = function;
}
protected BiFunction<Integer, Integer, Integer> getFunction() {
return function;
}
SegmentTree() {
}
SegmentTree(int[] startBase, int neutral, BiFunction<Integer, Integer, Integer> function) {
this.function = function;
int length = startBase.length;
int[] base;
if ((length & (length - 1)) != 0) {
int pow = 0;
while (length > 0) {
length >>= 1;
pow++;
}
pow--;
base = new int[2 << pow];
System.arraycopy(startBase, 0, base, 0, startBase.length);
Arrays.fill(base, startBase.length, base.length, neutral);
} else {
base = startBase;
}
segmentArray = new int[base.length << 1]; // maybe * 4
Arrays.fill(segmentArray, neutral);
inDepth(base, 1, 0, base.length - 1);
}
private void inDepth(int[] base, int position, int low, int high) {
if (low == high) {
segmentArray[position] = base[low];
} else {
int mid = (low + high) >> 1;
inDepth(base, position << 1, low, mid);
inDepth(base, (position << 1) + 1, mid + 1, high);
segmentArray[position] = function.apply(segmentArray[position << 1], segmentArray[(position << 1) + 1]);
}
}
protected int getValue(int left, int right, int neutral) {
return findValue(1, 0, ((segmentArray.length) >> 1) - 1, left, right, neutral);
}
private int findValue(int position, int low, int high, int left, int right, int neutral) {
if (left > right) {
return neutral;
}
if (left == low && right == high) {
return segmentArray[position];
}
int mid = (low + high) >> 1;
return function.apply(findValue(position << 1, low, mid, left, Math.min(right, mid), neutral),
findValue((position << 1) + 1, mid + 1, high, Math.max(left, mid + 1), right, neutral));
}
protected void replaceValue(int index, int value) {
update(1, 0, (segmentArray.length >> 1) - 1, index, value);
}
private void update(int position, int low, int high, int index, int value) {
if (low == high) {
segmentArray[position] = value;
} else {
int mid = (low + high) >> 1;
if (index <= mid) {
update(position << 1, low, mid, index, value);
} else {
update((position << 1) + 1, mid + 1, high, index, value);
}
segmentArray[position] = function.apply(segmentArray[position << 1], segmentArray[(position << 1) + 1]);
}
}
}
static class SegmentTreeGeneric<T> {
private Object[] segmentArray;
private BiFunction<T, T, T> function;
protected void setSegmentArray(T[] segmentArray) {
this.segmentArray = segmentArray;
}
protected Object getSegmentArray() {
return segmentArray.clone();
}
protected void setFunction(BiFunction<T, T, T> function) {
this.function = function;
}
protected BiFunction<T, T, T> getFunction() {
return function;
}
SegmentTreeGeneric() {
}
SegmentTreeGeneric(T[] startBase, T neutral, BiFunction<T, T, T> function) {
this.function = function;
int length = startBase.length;
Object[] base;
if ((length & (length - 1)) != 0) {
int pow = 0;
while (length > 0) {
length >>= 1;
pow++;
}
pow--;
base = new Object[2 << pow];
System.arraycopy(startBase, 0, base, 0, startBase.length);
Arrays.fill(base, startBase.length, base.length, neutral);
} else {
base = startBase;
}
segmentArray = new Object[base.length << 1]; // maybe * 4
Arrays.fill(segmentArray, neutral);
inDepth(base, 1, 0, base.length - 1);
}
private void inDepth(Object[] base, int position, int low, int high) {
if (low == high) {
segmentArray[position] = base[low];
} else {
int mid = (low + high) >> 1;
inDepth(base, position << 1, low, mid);
inDepth(base, (position << 1) + 1, mid + 1, high);
segmentArray[position] = function.apply((T) segmentArray[position << 1], (T) segmentArray[(position << 1) + 1]);
}
}
protected T getValue(int left, int right, T neutral) {
return findValue(1, 0, ((segmentArray.length) >> 1) - 1, left, right, neutral);
}
private T findValue(int position, int low, int high, int left, int right, T neutral) {
if (left > right) {
return neutral;
}
if (left == low && right == high) {
return (T) segmentArray[position];
}
int mid = (low + high) >> 1;
return function.apply(findValue(position << 1, low, mid, left, Math.min(right, mid), neutral),
findValue((position << 1) + 1, mid + 1, high, Math.max(left, mid + 1), right, neutral));
}
protected void replaceValue(int index, T value) {
update(1, 0, (segmentArray.length >> 1) - 1, index, value);
}
private void update(int position, int low, int high, int index, T value) {
if (low == high) {
segmentArray[position] = value;
} else {
int mid = (low + high) >> 1;
if (index <= mid) {
update(position << 1, low, mid, index, value);
} else {
update((position << 1) + 1, mid + 1, high, index, value);
}
segmentArray[position] = function.apply((T) segmentArray[position << 1], (T) segmentArray[(position << 1) + 1]);
}
}
}
}
class SystemOfDisjointSets {
private int[] rank;
private int[] ancestor;
SystemOfDisjointSets(int size) {
this.rank = new int[size];
this.ancestor = new int[size];
}
protected void makeSet(int value) {
ancestor[value] = value;
rank[value] = 0;
}
protected int findSet(int value) {
if (value == ancestor[value]) {
return value;
}
return ancestor[value] = findSet(ancestor[value]);
}
protected boolean mergeSets(int first, int second) {
first = findSet(first);
second = findSet(second);
if (first != second) {
if (rank[first] < rank[second]) {
int number = first;
first = second;
second = number;
}
ancestor[second] = first;
if (rank[first] == rank[second]) {
rank[first]++;
}
return true;
}
return false;
}
}
interface Array {
void useArray(int[] a);
}
interface Method {
void use();
}
class FastSort {
protected static int[] sort(int[] array, int ShellHeapMergeMyInsertionSort) {
sort(array, ShellHeapMergeMyInsertionSort, array.length);
return array;
}
protected static int[] sortClone(int[] array, int ShellHeapMergeMyInsertionSort) {
int[] base = array.clone();
sort(base, ShellHeapMergeMyInsertionSort, array.length);
return base;
}
private static void sort(int[] array, int ShellHeapMergeMyInsertionSort, int length) {
if (ShellHeapMergeMyInsertionSort < 0 || ShellHeapMergeMyInsertionSort > 4) {
Random random = new Random();
ShellHeapMergeMyInsertionSort = random.nextInt(4);
}
if (ShellHeapMergeMyInsertionSort == 0) {
ShellSort(array);
} else if (ShellHeapMergeMyInsertionSort == 1) {
HeapSort(array);
} else if (ShellHeapMergeMyInsertionSort == 2) {
MergeSort(array, 0, length - 1);
} else if (ShellHeapMergeMyInsertionSort == 3) {
straightMergeSort(array, length);
} else if (ShellHeapMergeMyInsertionSort == 4) {
insertionSort(array);
}
}
private static void straightMergeSort(int[] array, int size) {
if (size == 0) {
return;
}
int length = (size >> 1) + ((size % 2) == 0 ? 0 : 1);
Integer[][] ZeroBuffer = new Integer[length + length % 2][2];
Integer[][] FirstBuffer = new Integer[0][0];
for (int index = 0; index < length; index++) {
int ArrayIndex = index << 1;
int NextArrayIndex = (index << 1) + 1;
if (NextArrayIndex < size) {
if (array[ArrayIndex] > array[NextArrayIndex]) {
ZeroBuffer[index][0] = array[NextArrayIndex];
ZeroBuffer[index][1] = array[ArrayIndex];
} else {
ZeroBuffer[index][0] = array[ArrayIndex];
ZeroBuffer[index][1] = array[NextArrayIndex];
}
} else {
ZeroBuffer[index][0] = array[ArrayIndex];
}
}
boolean position = false;
int pointer0, pointer, pointer1, number = 4, NewPointer, count;
Integer[][] NewBuffer;
Integer[][] OldBuffer;
length = (size >> 2) + ((size % 4) == 0 ? 0 : 1);
while (true) {
pointer0 = 0;
count = (number >> 1) - 1;
if (!position) {
FirstBuffer = new Integer[length + length % 2][number];
NewBuffer = FirstBuffer;
OldBuffer = ZeroBuffer;
} else {
ZeroBuffer = new Integer[length + length % 2][number];
NewBuffer = ZeroBuffer;
OldBuffer = FirstBuffer;
}
for (int i = 0; i < length; i++) {
pointer = 0;
pointer1 = 0;
NewPointer = pointer0 + 1;
if (length == 1) {
for (int g = 0; g < size; g++) {
if (pointer > count || OldBuffer[pointer0][pointer] == null) {
array[g] = OldBuffer[NewPointer][pointer1];
pointer1++;
} else if (pointer1 > count || OldBuffer[NewPointer][pointer1] == null) {
if (OldBuffer[pointer0][pointer] == null) {
continue;
}
array[g] = OldBuffer[pointer0][pointer];
pointer++;
} else if (OldBuffer[pointer0][pointer] >= OldBuffer[NewPointer][pointer1]) {
array[g] = OldBuffer[NewPointer][pointer1];
pointer1++;
} else {
array[g] = OldBuffer[pointer0][pointer];
pointer++;
}
}
return;
}
for (int g = 0; g < number; g++) {
if (pointer > count || OldBuffer[pointer0][pointer] == null) {
if (OldBuffer[NewPointer][pointer1] == null) {
continue;
}
NewBuffer[i][g] = OldBuffer[NewPointer][pointer1];
pointer1++;
} else if (pointer1 > count || OldBuffer[NewPointer][pointer1] == null) {
if (OldBuffer[pointer0][pointer] == null) {
continue;
}
NewBuffer[i][g] = OldBuffer[pointer0][pointer];
pointer++;
} else if (OldBuffer[pointer0][pointer] >= OldBuffer[NewPointer][pointer1]) {
NewBuffer[i][g] = OldBuffer[NewPointer][pointer1];
pointer1++;
} else {
NewBuffer[i][g] = OldBuffer[pointer0][pointer];
pointer++;
}
}
pointer0 += 2;
}
position = !position;
length = (length >> 1) + length % 2;
number <<= 1;
}
}
private static void ShellSort(int[] array) {
int j;
for (int gap = (array.length >> 1); gap > 0; gap >>= 1) {
for (int i = gap; i < array.length; i++) {
int temp = array[i];
for (j = i; j >= gap && array[j - gap] > temp; j -= gap) {
array[j] = array[j - gap];
}
array[j] = temp;
}
}
}
private static void HeapSort(int[] array) {
for (int i = (array.length >> 1) - 1; i >= 0; i--)
shiftDown(array, i, array.length);
for (int i = array.length - 1; i > 0; i--) {
swap(array, 0, i);
shiftDown(array, 0, i);
}
}
private static void shiftDown(int[] array, int i, int n) {
int child;
int tmp;
for (tmp = array[i]; leftChild(i) < n; i = child) {
child = leftChild(i);
if (child != n - 1 && (array[child] < array[child + 1]))
child++;
if (tmp < array[child])
array[i] = array[child];
else
break;
}
array[i] = tmp;
}
private static int leftChild(int i) {
return (i << 1) + 1;
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static void MergeSort(int[] array, int low, int high) {
if (low < high) {
int mid = (low + high) >> 1;
MergeSort(array, low, mid);
MergeSort(array, mid + 1, high);
merge(array, low, mid, high);
}
}
private static void merge(int[] array, int low, int mid, int high) {
int n = high - low + 1;
int[] Temp = new int[n];
int i = low, j = mid + 1;
int k = 0;
while (i <= mid || j <= high) {
if (i > mid)
Temp[k++] = array[j++];
else if (j > high)
Temp[k++] = array[i++];
else if (array[i] < array[j])
Temp[k++] = array[i++];
else
Temp[k++] = array[j++];
}
for (j = 0; j < n; j++)
array[low + j] = Temp[j];
}
private static void insertionSort(int[] elements) {
for (int i = 1; i < elements.length; i++) {
int key = elements[i];
int j = i - 1;
while (j >= 0 && key < elements[j]) {
elements[j + 1] = elements[j];
j--;
}
elements[j + 1] = key;
}
}
}
class IO {
private static BufferedReader read;
private static boolean fileInput = false;
private static BufferedWriter write;
private static boolean fileOutput = false;
public static void setFileInput(boolean fileInput) {
IO.fileInput = fileInput;
}
public static void setFileOutput(boolean fileOutput) {
IO.fileOutput = fileOutput;
}
private static void startInput() {
try {
read = new BufferedReader(fileInput ? new FileReader("input.txt") : new InputStreamReader(System.in));
} catch (Exception error) {
}
}
private static void startOutput() {
try {
write = new BufferedWriter(fileOutput ? new FileWriter("output.txt") : new OutputStreamWriter(System.out));
} catch (Exception error) {
}
}
protected static int readInt() throws Exception {
if (read == null) {
startInput();
}
return Integer.parseInt(read.readLine());
}
protected static long readLong() throws Exception {
if (read == null) {
startInput();
}
return Long.parseLong(read.readLine());
}
protected static String readString() throws Exception {
if (read == null) {
startInput();
}
return read.readLine();
}
protected static int[] readArrayInt(String split) throws Exception {
if (read == null) {
startInput();
}
return Arrays.stream(read.readLine().split(split)).mapToInt(Integer::parseInt).toArray();
}
protected static long[] readArrayLong(String split) throws Exception {
if (read == null) {
startInput();
}
return Arrays.stream(read.readLine().split(split)).mapToLong(Long::parseLong).toArray();
}
protected static String[] readArrayString(String split) throws Exception {
if (read == null) {
startInput();
}
return read.readLine().split(split);
}
protected static void writeArray(int[] array, String split, boolean enter) {
if (write == null) {
startOutput();
}
try {
int length = array.length;
for (int index = 0; index < length; index++) {
write.write(Integer.toString(array[index]));
if (index + 1 != length) {
write.write(split);
}
}
if (enter) {
writeEnter();
}
} catch (Exception error) {
}
}
protected static void writeArray(Integer[] array, String split, boolean enter) {
if (write == null) {
startOutput();
}
try {
int length = array.length;
for (int index = 0; index < length; index++) {
write.write(Integer.toString(array[index]));
if (index + 1 != length) {
write.write(split);
}
}
if (enter) {
writeEnter();
}
} catch (Exception error) {
}
}
protected static void writeArray(Int[] array, String split, boolean enter) {
if (write == null) {
startOutput();
}
try {
int length = array.length;
for (int index = 0; index < length; index++) {
write.write(Integer.toString(array[index].value));
if (index + 1 != length) {
write.write(split);
}
}
if (enter) {
writeEnter();
}
} catch (Exception error) {
}
}
protected static void writeArray(long[] array, String split, boolean enter) {
if (write == null) {
startOutput();
}
try {
int length = array.length;
for (int index = 0; index < length; index++) {
write.write(Long.toString(array[index]));
if (index + 1 != length) {
write.write(split);
}
}
if (enter) {
writeEnter();
}
} catch (Exception error) {
}
}
protected static void writeArray(Long[] array, String split, boolean enter) {
if (write == null) {
startOutput();
}
try {
int length = array.length;
for (int index = 0; index < length; index++) {
write.write(Long.toString(array[index]));
if (index + 1 != length) {
write.write(split);
}
}
if (enter) {
writeEnter();
}
} catch (Exception error) {
}
}
public static void writeArray(String[] array, String split, boolean enter) {
if (write == null) {
startOutput();
}
try {
int length = array.length;
for (int index = 0; index < length; index++) {
write.write(array[index]);
if (index + 1 != length) {
write.write(split);
}
}
if (enter) {
writeEnter();
}
} catch (Exception ignored) {
}
}
protected static void writeArray(boolean[] array, String split, boolean enter) {
if (write == null) {
startOutput();
}
try {
int length = array.length;
for (int index = 0; index < length; index++) {
write.write(Boolean.toString(array[index]));
if (index + 1 != length) {
write.write(split);
}
}
if (enter) {
writeEnter();
}
} catch (Exception ignored) {
}
}
protected static void writeInt(int number, String end) {
if (write == null) {
startOutput();
}
try {
write.write(Integer.toString(number));
write.write(end);
} catch (Exception ignored) {
}
}
protected static void writeInt(Integer number, String end) {
if (write == null) {
startOutput();
}
try {
write.write(Integer.toString(number));
write.write(end);
} catch (Exception ignored) {
}
}
protected static void writeLong(long number, String end) {
if (write == null) {
startOutput();
}
try {
write.write(Long.toString(number));
write.write(end);
} catch (Exception ignored) {
}
}
protected static void writeLong(Long number, String end) {
if (write == null) {
startOutput();
}
try {
write.write(Long.toString(number));
write.write(end);
} catch (Exception ignored) {
}
}
protected static void writeString(String word, String end) {
if (write == null) {
startOutput();
}
try {
write.write(word);
write.write(end);
} catch (Exception ignored) {
}
}
protected static void writeBoolean(boolean value, String end) {
if (write == null) {
startOutput();
}
try {
write.write(value ? "true" : "false");
write.write(end);
} catch (Exception ignored) {
}
}
protected static void writeBoolean(Boolean value, String end) {
if (write == null) {
startOutput();
}
try {
write.write(value ? "true" : "false");
write.write(end);
} catch (Exception ignored) {
}
}
protected static void writeChar(char word, String end) {
if (write == null) {
startOutput();
}
try {
write.write(word);
write.write(end);
} catch (Exception ignored) {
}
}
protected static void writeChar(Character word, String end) {
if (write == null) {
startOutput();
}
try {
write.write(word);
write.write(end);
} catch (Exception ignored) {
}
}
protected static void writeEnter() {
if (write == null) {
startOutput();
}
try {
write.newLine();
} catch (Exception ignored) {
}
}
protected static void print(boolean exit) throws Exception {
if (exit) {
print();
} else {
write.flush();
}
}
protected static void print() throws Exception {
if (write == null) {
return;
}
write.flush();
if (read != null) {
read.close();
}
write.close();
}
}
| Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | b90f5be3c5f832336bdd4ab8493b3ef9 | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | import java.util.Scanner;
public class Solution2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int tests = scanner.nextInt();
for (int t = 0; t < tests; t++) {
int n = scanner.nextInt();
long[] nums = new long[n];
long totalSum = 0;
long maxSum0 = 0, currSum0 = 0;
long maxSum1 = 0, currSum1 = 0;
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextLong();
totalSum += nums[i];
if (i < n-1 && currSum0 + nums[i] >= 0) {
currSum0 += nums[i];
} else {
currSum0 = 0;
}
if (i > 0 && currSum1 + nums[i] >= 0) {
currSum1 += nums[i];
} else {
currSum1 = 0;
}
if (currSum0 > maxSum0) {
maxSum0 = currSum0;
}
if (currSum1 > maxSum1) {
maxSum1 = currSum1;
}
}
System.out.println(totalSum > Math.max(maxSum0, maxSum1) ? "YES" : "NO");
}
}
} | Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | 25cb3d2874f491dd9b8a32975c3f0738 | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.StringTokenizer;
public class Solution{
public static void main(String[] args) throws Exception{
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int tt = fs.nextInt();
while(tt-->0) {
int n = fs.nextInt();
int[] arr = fs.readArray(n);
boolean bool = true;
long sum = 0;
for(int i=0;i<n-1;i++) {
sum += arr[i];
if(sum<=0) {
bool = false;
break;
}
}
sum = 0;
for(int i=n-1;i>0;i--) {
sum += arr[i];
if(sum<=0) {
bool = false;
break;
}
}
out.println(bool?"YES":"NO");
}
out.close();
}
static class FastScanner{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next(){
while(!st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
} catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt(){
return Integer.parseInt(next());
}
public int[] readArray(int n){
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = nextInt();
return a;
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | 8b7fe507db7fe5ceea1bb4990adf4167 | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes |
//normal
import java.util.*;
import java.lang.*;
import java.io.*;
// String Tokenizer
public class Main {
public static void main(String[] args) {
// code
Scanner scn = new Scanner(System.in);
// System.out.println("Hi");
int t = scn.nextInt();
while (t > 0) {
t--;
int n = scn.nextInt();
int[] arr = new int[n];
long sum = 0;
for (int i = 0; i < n; i++) {
arr[i] = scn.nextInt();
sum += arr[i];
}
long curr_sum = 0;
long max_sum1 = 0;
for (int i = 1; i < n; i++) {
if (arr[i] + curr_sum < 0) {
curr_sum = 0;
continue;
} else {
curr_sum += arr[i];
}
if (curr_sum > max_sum1) {
max_sum1 = curr_sum;
}
}
long max_sum2 = 0;
curr_sum = 0;
for (int i = 0; i < n - 1; i++) {
if (arr[i] + curr_sum < 0) {
continue;
} else {
curr_sum += arr[i];
}
if (curr_sum > max_sum2) {
max_sum2 = curr_sum;
}
}
long max_sum = Math.max(max_sum1, max_sum2);
//System.out.println(max_sum);
if (sum > max_sum) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
} | Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | 0772ffc960f50b8c6629293fd45d1006 | train_004.jsonl | 1578665100 | Today, Yasser and Adel are at the shop buying cupcakes. There are $$$n$$$ cupcake types, arranged from $$$1$$$ to $$$n$$$ on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type $$$i$$$ is an integer $$$a_i$$$. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment $$$[l, r]$$$ $$$(1 \le l \le r \le n)$$$ that does not include all of cupcakes (he can't choose $$$[l, r] = [1, n]$$$) and buy exactly one cupcake of each of types $$$l, l + 1, \dots, r$$$.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be $$$[7, 4, -1]$$$. Yasser will buy all of them, the total tastiness will be $$$7 + 4 - 1 = 10$$$. Adel can choose segments $$$[7], [4], [-1], [7, 4]$$$ or $$$[4, -1]$$$, their total tastinesses are $$$7, 4, -1, 11$$$ and $$$3$$$, respectively. Adel can choose segment with tastiness $$$11$$$, and as $$$10$$$ is not strictly greater than $$$11$$$, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
StringBuilder sb = new StringBuilder("");
int t = Integer.parseInt(br.readLine());
while(t-- != 0) {
int n = Integer.parseInt(br.readLine());
int a[] = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0 ; i < n ; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
System.out.println(Code(a , n));
}
}
static String Code(int[] a , int n) {
long full = 0;
for(int i = 0 ; i < n ; i++) {
full += a[i];
}
long curSum = 0 , maxSum = a[0];
int maxInd = 0;
boolean cameHere = false;
for(int i = 0 ; i < n ; i++) {
curSum += a[i];
if(curSum > maxSum) {
maxSum = curSum;
maxInd = i;
}
if(curSum <= 0) {
cameHere = true;
curSum = 0;
}
}
//System.out.println(maxInd + " " + cameHere);
//System.out.println("full " + full + " , " + " maxSum " + maxSum);
if(full == maxSum) {
return maxInd != n - 1 || (maxInd == n - 1 && cameHere) ? "NO" : "YES";
}
return full > maxSum ? "YES" : "NO";
}
}
/*
1
10
10 5 -12 7 -10 20 30 -10 50 60
*/ | Java | ["3\n4\n1 2 3 4\n3\n7 4 -1\n3\n5 -5 5"] | 1 second | ["YES\nNO\nNO"] | NoteIn the first example, the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example, Adel will choose the segment $$$[1, 2]$$$ with total tastiness $$$11$$$, which is not less than the total tastiness of all cupcakes, which is $$$10$$$.In the third example, Adel can choose the segment $$$[3, 3]$$$ with total tastiness of $$$5$$$. Note that Yasser's cupcakes' total tastiness is also $$$5$$$, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes. | Java 11 | standard input | [
"dp",
"implementation",
"greedy"
] | 6e5b4d43e64645cf26d5eac31437b1a9 | Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ represents the tastiness of the $$$i$$$-th type of cupcake. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$. | 1,300 | For each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO". | standard output | |
PASSED | 53bce06c85701e9a3d8c8e5569569350 | train_004.jsonl | 1553965800 | Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 < i_2 < \ldots < i_k \leq r$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf1142b_2 {
public static void main(String[] args) throws IOException {
int n = rni(), m = ni(), q = ni(), p[] = riam1(n), last_of[] = new int[n], a[] = riam1(m), last_ind[] = new int[n], last[][] = new int[m][20], dp[] = new int[m];
for (int i = 0; i < n; ++i) last_of[p[(i + 1) % n]] = p[i];
fill(last_ind, -1);
for (int[] row : last) row[0] = -1;
for (int i = 0; i < m; ++i) {
last[i][0] = last_ind[last_of[a[i]]];
last_ind[a[i]] = i;
}
for (int i = 1; i < 20; ++i) for (int j = 0; j < m; ++j) last[j][i] = last[j][i - 1] == -1 ? -1 : last[last[j][i - 1]][i - 1];
for (int i = 0; i < m; ++i) dp[i] = i;
for (int i = 0; i < 20; ++i) if (((n - 1) & (1 << i)) > 0) for (int j = 0; j < m; ++j) dp[j] = dp[j] == -1 ? -1 : last[dp[j]][i];
for (int i = 1; i < m; ++i) dp[i] = max(dp[i - 1], dp[i]);
while (q --> 0) {
int l = rni() - 1, r = ni() - 1;
pr(dp[r] >= l ? 1 : 0);
}
prln();
close();
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int) d;}
static int cei(double d) {return (int) ceil(d);}
static long fll(double d) {return (long) d;}
static long cel(double d) {return (long) ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static double rd() throws IOException {return Double.parseDouble(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}
static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {prln("yes");}
static void pry() {prln("Yes");}
static void prY() {prln("YES");}
static void prno() {prln("no");}
static void prn() {prln("No");}
static void prN() {prln("NO");}
static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;};
static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;}
static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;}
static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}
static void h() {prln("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | Java | ["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"] | 2 seconds | ["110", "010"] | NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation. | Java 11 | standard input | [
"dp",
"math",
"data structures",
"dfs and similar",
"trees"
] | 4aaeff1b38d501daf9a877667e075d49 | The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive. | 2,000 | Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise. | standard output | |
PASSED | ad3fd95cdc1e946cebf0829c539f7e44 | train_004.jsonl | 1553965800 | Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation $$$p$$$ of length $$$n$$$, and Skynyrd bought an array $$$a$$$ of length $$$m$$$, consisting of integers from $$$1$$$ to $$$n$$$. Lynyrd and Skynyrd became bored, so they asked you $$$q$$$ queries, each of which has the following form: "does the subsegment of $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, have a subsequence that is a cyclic shift of $$$p$$$?" Please answer the queries.A permutation of length $$$n$$$ is a sequence of $$$n$$$ integers such that each integer from $$$1$$$ to $$$n$$$ appears exactly once in it.A cyclic shift of a permutation $$$(p_1, p_2, \ldots, p_n)$$$ is a permutation $$$(p_i, p_{i + 1}, \ldots, p_{n}, p_1, p_2, \ldots, p_{i - 1})$$$ for some $$$i$$$ from $$$1$$$ to $$$n$$$. For example, a permutation $$$(2, 1, 3)$$$ has three distinct cyclic shifts: $$$(2, 1, 3)$$$, $$$(1, 3, 2)$$$, $$$(3, 2, 1)$$$.A subsequence of a subsegment of array $$$a$$$ from the $$$l$$$-th to the $$$r$$$-th positions, inclusive, is a sequence $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$ for some $$$i_1, i_2, \ldots, i_k$$$ such that $$$l \leq i_1 < i_2 < \ldots < i_k \leq r$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class B549
{
public static void main(String [] args)
{
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt(); int m = sc.nextInt(); int q = sc.nextInt();
int [] prev = new int [n+1]; int [] perm = new int[n];
for (int i = 0; i < n; i++) {
perm[i] = sc.nextInt();
if (i > 0) {
prev[perm[i]] = perm[i-1];
}
}
prev[perm[0]] = perm[n-1]; int [] a = new int[m];
for (int i = 0; i < m; i++) a[i] = sc.nextInt();
int [] closest = new int[n+1];
Arrays.fill(closest, - 1);
int [] parent = new int[m];
for (int i = 0; i < m; i++) {
parent[i] = closest[prev[a[i]]];
closest[a[i]] = i;
}
int log = (int) (Math.log10(m) / Math.log10(2)) + 1;
int [][] memo = new int[m][log + 1];
for (int [] arr: memo) Arrays.fill(arr, -1);
for (int i = 0; i < m; i++) {
memo[i][0] = parent[i];
for (int j = 1; j <= log; j++) {
if (memo[i][j-1] == -1) {
memo[i][j] = -1;
} else {
memo[i][j] = memo[memo[i][j - 1]][j - 1];
}
}
}
int [] ret = new int[m];
for (int i = 0; i < m; i++) {
int jump = n - 1; int cur = i;
for (int x = log; x >= 0; x--) {
if (((jump & (1 << x)) >> x) == 1) {
cur = memo[cur][x];
}
if (cur == -1) break;
}
ret[i] = cur;
}
RangeTree seg = new RangeTree(m);
for (int i = 0; i < m; i++) seg.update(i, i, ret[i]);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < q; i++) {
int l = sc.nextInt() - 1; int r = sc.nextInt() - 1;
long best = seg.maxQuery(l, r);
if (best >= l || n == 1) sb.append(1); else sb.append(0);
}
out.println(sb.toString());
out.close();
}
static class RangeTree {
private long[] max;
private long[] min;
private long[] lazy;
private long[] sum;
private int size;
public RangeTree(int size) {
this.size = size;
max = new long[4*size];
min = new long[4*size];
sum = new long[4*size];
lazy = new long[4*size];
}
public void update(int l, int r, int inc) {
update(1, 0, size-1, l, r, inc);
}
private void pushDown(int index, int l, int r) {
min[index] += lazy[index];
max[index] += lazy[index];
sum[index] += lazy[index] * (r-l+1);
if(l != r) {
lazy[2*index] += lazy[index];
lazy[2*index+1] += lazy[index];
}
lazy[index] = 0;
}
private void pullUp(int index, int l, int r) {
int m = (l+r)/2;
min[index] = Math.min(evaluateMin(2*index, l, m), evaluateMin(2*index+1, m+1, r));
max[index] = Math.max(evaluateMax(2*index, l, m), evaluateMax(2*index+1, m+1, r));
sum[index] = evaluateSum(2*index, l, m) + evaluateSum(2*index+1, m+1, r);
}
private long evaluateSum(int index, int l, int r) {
return sum[index] + (r-l+1)*lazy[index];
}
private long evaluateMin(int index, int l, int r) {
return min[index] + lazy[index];
}
private long evaluateMax(int index, int l, int r) {
return max[index] + lazy[index];
}
private void update(int index, int l, int r, int left, int right, int inc) {
if(r < left || l > right) return;
if(l >= left && r <= right) {
lazy[index] += inc;
return;
}
pushDown(index, l, r);
int m = (l+r)/2;
update(2*index, l, m, left, right, inc);
update(2*index+1, m+1, r, left, right, inc);
pullUp(index, l, r);
}
public long minQuery(int l, int r) {
return minQuery(1, 0, size-1, l, r);
}
private long minQuery(int index, int l, int r, int left, int right) {
if(r < left || l > right) return Long.MAX_VALUE;
if(l >= left && r <= right) {
return evaluateMin(index, l, r);
}
pushDown(index, l, r);
int m = (l+r)/2;
long ret = Long.MAX_VALUE;
ret = Math.min(ret, minQuery(2*index, l, m, left, right));
ret = Math.min(ret, minQuery(2*index+1, m+1, r, left, right));
pullUp(index, l, r);
return ret;
}
public long maxQuery(int l, int r) {
return maxQuery(1, 0, size-1, l, r);
}
private long maxQuery(int index, int l, int r, int left, int right) {
if(r < left || l > right) return Long.MIN_VALUE;
if(l >= left && r <= right) {
return evaluateMax(index, l, r);
}
pushDown(index, l, r);
int m = (l+r)/2;
long ret = Long.MIN_VALUE;
ret = Math.max(ret, maxQuery(2*index, l, m, left, right));
ret = Math.max(ret, maxQuery(2*index+1, m+1, r, left, right));
pullUp(index, l, r);
return ret;
}
public long sumQuery(int l, int r) {
return sumQuery(1, 0, size-1, l, r);
}
private long sumQuery(int index, int l, int r, int left, int right) {
if(r < left || l > right) return 0;
if(l >= left && r <= right) {
return evaluateSum(index, l, r);
}
pushDown(index, l, r);
int m = (l+r)/2;
long ret = 0;
ret += sumQuery(2*index, l, m, left, right);
ret += sumQuery(2*index+1, m+1, r, left, right);
pullUp(index, l, r);
return ret;
}
}
//-----------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 | ["3 6 3\n2 1 3\n1 2 3 1 2 3\n1 5\n2 6\n3 5", "2 4 3\n2 1\n1 1 2 2\n1 2\n2 3\n3 4"] | 2 seconds | ["110", "010"] | NoteIn the first example the segment from the $$$1$$$-st to the $$$5$$$-th positions is $$$1, 2, 3, 1, 2$$$. There is a subsequence $$$1, 3, 2$$$ that is a cyclic shift of the permutation. The subsegment from the $$$2$$$-nd to the $$$6$$$-th positions also contains a subsequence $$$2, 1, 3$$$ that is equal to the permutation. The subsegment from the $$$3$$$-rd to the $$$5$$$-th positions is $$$3, 1, 2$$$, there is only one subsequence of length $$$3$$$ ($$$3, 1, 2$$$), but it is not a cyclic shift of the permutation.In the second example the possible cyclic shifts are $$$1, 2$$$ and $$$2, 1$$$. The subsegment from the $$$1$$$-st to the $$$2$$$-nd positions is $$$1, 1$$$, its subsequences are not cyclic shifts of the permutation. The subsegment from the $$$2$$$-nd to the $$$3$$$-rd positions is $$$1, 2$$$, it coincides with the permutation. The subsegment from the $$$3$$$ to the $$$4$$$ positions is $$$2, 2$$$, its subsequences are not cyclic shifts of the permutation. | Java 11 | standard input | [
"dp",
"math",
"data structures",
"dfs and similar",
"trees"
] | 4aaeff1b38d501daf9a877667e075d49 | The first line contains three integers $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \le n, m, q \le 2 \cdot 10^5$$$) — the length of the permutation $$$p$$$, the length of the array $$$a$$$ and the number of queries. The next line contains $$$n$$$ integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th of them is the $$$i$$$-th element of the permutation. Each integer from $$$1$$$ to $$$n$$$ appears exactly once. The next line contains $$$m$$$ integers from $$$1$$$ to $$$n$$$, the $$$i$$$-th of them is the $$$i$$$-th element of the array $$$a$$$. The next $$$q$$$ lines describe queries. The $$$i$$$-th of these lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$), meaning that the $$$i$$$-th query is about the subsegment of the array from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive. | 2,000 | Print a single string of length $$$q$$$, consisting of $$$0$$$ and $$$1$$$, the digit on the $$$i$$$-th positions should be $$$1$$$, if the subsegment of array $$$a$$$ from the $$$l_i$$$-th to the $$$r_i$$$-th positions, inclusive, contains a subsequence that is a cyclic shift of $$$p$$$, and $$$0$$$ otherwise. | standard output | |
PASSED | a5a9fc233373942c07b9230a7e3e9e82 | train_004.jsonl | 1470578700 | Natalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form:Where represents logical OR and represents logical exclusive OR (XOR), and vi, j are some boolean variables or their negations. Natalia calls the left side of the equation a XNF formula. Each statement in brackets is called a clause, and vi, j are called literals.In the equation Natalia has, the left side is actually a 2-XNF-2 containing variables x1, x2, ..., xm and their negations. An XNF formula is 2-XNF-2 if: For each 1 ≤ i ≤ n, ki ≤ 2, i.e. the size of each clause doesn't exceed two. Each variable occurs in the formula at most two times (with negation and without negation in total). Please note that it's possible that a variable occurs twice but its negation doesn't occur in any clause (or vice versa). Natalia is given a formula of m variables, consisting of n clauses. Please, make sure to check the samples in order to properly understand how the formula looks like.Natalia is more into fight than theory, so she asked you to tell her the number of answers to this equation. More precisely, you need to find the number of ways to set x1, ..., xm with true and false (out of total of 2m ways) so that the equation is satisfied. Since this number can be extremely large, you need to print the answer modulo 109 + 7.Please, note that some variable may appear twice in one clause, or not appear in the equation at all (but still, setting it to false or true gives different ways to set variables). | 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.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 Jialin Ouyang (Jialin.Ouyang@gmail.com)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
QuickWriter out = new QuickWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int n;
int m;
int[] singlePositive;
int[] singleNegative;
boolean[] visited;
BidirectionalGraph<XnfEdge> graph;
public void solve(int testNumber, QuickScanner in, QuickWriter out) {
m = in.nextInt();
n = in.nextInt();
graph = new BidirectionalGraph<>(n, m);
graph.init(n);
singlePositive = new int[n];
singleNegative = new int[n];
visited = new boolean[n];
for (int i = 0; i < m; ++i) {
if (in.nextInt() == 1) {
int x = in.nextInt();
if (x > 0) {
++singlePositive[x - 1];
} else {
++singleNegative[-x - 1];
}
} else {
int x = in.nextInt();
int y = in.nextInt();
graph.add(
new XnfEdge(Math.abs(x) - 1, Math.abs(y) - 1, x < 0, y < 0),
new XnfEdge(Math.abs(y) - 1, Math.abs(x) - 1, y < 0, x < 0));
}
}
Way res = Way.way[1][0];
// Single
for (int i = 0; i < n; ++i)
if (graph.outDegree[i] == 0) {
visited[i] = true;
res = res.mul(Way.createSingle(singlePositive[i], singleNegative[i]));
}
// Chain
for (int i = 0; i < n; ++i)
if (!visited[i] && graph.outDegree[i] == 1) {
res = res.mul(dfsChain(i, null, null));
}
// Self loop
for (int i = 0; i < n; ++i)
if (!visited[i] && graph.lastOutgoingEdge(i).toIdx == i) {
visited[i] = true;
XnfEdge edge = graph.lastOutgoingEdge(i);
res = res.mul(Way.createSelfLoop(
(edge.fromNeg ? 1 : 0) | (edge.toNeg ? 1 : 0),
(edge.fromNeg ? 0 : 1) | (edge.toNeg ? 0 : 1)));
}
// Loop
for (int i = 0; i < n; ++i)
if (!visited[i]) {
res = res.mul(dfsLoop(i, null, null));
}
out.println(res.odd);
}
Way dfsChain(int u, Way[] ways, XnfEdge prevEdge) {
visited[u] = true;
Way[] nxtWays;
if (prevEdge == null) {
nxtWays = new Way[]{
Way.createChain(0, singlePositive[u], singleNegative[u]),
Way.createChain(1, singlePositive[u], singleNegative[u])};
} else {
nxtWays = new Way[]{
ways[0].mul(Way.createChain(0, 0, prevEdge, singlePositive[u], singleNegative[u])).add(
ways[1].mul(Way.createChain(1, 0, prevEdge, singlePositive[u], singleNegative[u]))),
ways[0].mul(Way.createChain(0, 1, prevEdge, singlePositive[u], singleNegative[u])).add(
ways[1].mul(Way.createChain(1, 1, prevEdge, singlePositive[u], singleNegative[u])))};
}
for (XnfEdge edge = graph.lastOutgoingEdge(u); edge != null; edge = (XnfEdge) edge.nextOutgoing) {
if (edge.reverse != prevEdge) {
return dfsChain(edge.toIdx, nxtWays, edge);
}
}
return nxtWays[0].add(nxtWays[1]);
}
Way dfsLoop(int u, Way[][] ways, XnfEdge prevEdge) {
visited[u] = true;
XnfEdge nxtEdge = null;
for (XnfEdge edge = graph.lastOutgoingEdge(u); edge != null; edge = (XnfEdge) edge.nextOutgoing) {
if (edge.reverse != prevEdge) {
nxtEdge = edge;
break;
}
}
if (prevEdge == null) {
return dfsLoop(
nxtEdge.toIdx,
new Way[][]{
{Way.way[1][0], Way.way[0][0]},
{Way.way[0][0], Way.way[1][0]}},
nxtEdge);
}
Way[][] nxtWays = new Way[][]{{Way.way[0][0], Way.way[0][0]}, {Way.way[0][0], Way.way[0][0]}};
if (!visited[nxtEdge.toIdx]) {
for (int start = 0; start < 2; ++start) {
for (int prevValue = 0; prevValue < 2; ++prevValue) {
for (int value = 0; value < 2; ++value) {
nxtWays[start][value] = nxtWays[start][value].add(
ways[start][prevValue].mul(Way.createLoop(prevValue, value, prevEdge)));
}
}
}
return dfsLoop(nxtEdge.toIdx, nxtWays, nxtEdge);
}
Way res = Way.way[0][0];
for (int start = 0; start < 2; ++start) {
for (int prevValue = 0; prevValue < 2; ++prevValue) {
for (int value = 0; value < 2; ++value) {
res = res.add(ways[start][prevValue].mul(Way.createLoopEnd(prevValue, value, start, prevEdge, nxtEdge)));
}
}
}
return res;
}
}
static class BidirectionalGraph<EDGE extends BidirectionalGraphEdge> extends DirectedGraph<EDGE> {
public BidirectionalGraph(int vertexCapacity, int edgeCapacity) {
super(vertexCapacity, edgeCapacity << 1);
}
public void add(EDGE edge, EDGE reverseEdge) {
add(edge);
add(reverseEdge);
edge.reverse = reverseEdge;
reverseEdge.reverse = edge;
}
}
static class BidirectionalGraphEdge extends DirectedGraphEdge {
public BidirectionalGraphEdge reverse;
public BidirectionalGraphEdge(int fromIdx, int toIdx) {
super(fromIdx, toIdx);
}
}
static class IntUtils {
private static final int MOD = 1000000007;
public static int add(int a, int b) {
return add(a, b, MOD);
}
public static int add(int a, int b, int mod) {
a += b;
return a >= mod ? a - mod : a;
}
public static int mul(int a, int b) {
return mul(a, b, MOD);
}
public static int mul(int a, int b, int mod) {
return a > 0
? (
b < mod / a
? a * b
: (int) ((long) a * b % mod))
: 0;
}
}
static class DirectedGraphEdge {
public int fromIdx;
public int toIdx;
public DirectedGraphEdge nextOutgoing;
public DirectedGraphEdge nextIncoming;
public DirectedGraphEdge(int fromIdx, int toIdx) {
this.fromIdx = fromIdx;
this.toIdx = toIdx;
}
}
static class QuickWriter {
private final PrintWriter writer;
public QuickWriter(OutputStream outputStream) {
this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public QuickWriter(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.print('\n');
}
public void close() {
writer.close();
}
}
static class DirectedGraph<EDGE extends DirectedGraphEdge> {
public int vertexCnt;
public List<EDGE> edges;
public int[] inDegree;
public int[] outDegree;
private List<EDGE> lastOutgoingEdge;
private List<EDGE> lastIncomingEdge;
public DirectedGraph(int vertexCapacity, int edgeCapacity) {
edges = new ArrayList<>(edgeCapacity);
lastOutgoingEdge = new ArrayList<>(vertexCapacity);
lastIncomingEdge = new ArrayList<>(vertexCapacity);
inDegree = new int[vertexCapacity];
outDegree = new int[vertexCapacity];
}
public void init(int vertexCnt) {
this.vertexCnt = vertexCnt;
edges.clear();
lastOutgoingEdge.clear();
lastIncomingEdge.clear();
Arrays.fill(inDegree, 0, vertexCnt, 0);
Arrays.fill(outDegree, 0, vertexCnt, 0);
for (int i = 0; i < vertexCnt; ++i) {
lastOutgoingEdge.add(null);
lastIncomingEdge.add(null);
}
}
public void add(EDGE edge) {
edges.add(edge);
int fromIdx = edge.fromIdx;
int toIdx = edge.toIdx;
edge.nextOutgoing = lastOutgoingEdge.get(fromIdx);
lastOutgoingEdge.set(fromIdx, edge);
edge.nextIncoming = lastIncomingEdge.get(toIdx);
lastIncomingEdge.set(toIdx, edge);
++inDegree[toIdx];
++outDegree[fromIdx];
}
public EDGE lastOutgoingEdge(int vertexIdx) {
return lastOutgoingEdge.get(vertexIdx);
}
}
static class Way {
public static final Way[][] way;
final int even;
final int odd;
static {
way = new Way[3][3];
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j) {
way[i][j] = new Way(i, j);
}
}
public Way() {
this(0, 0);
}
private Way(int even, int odd) {
this.even = even;
this.odd = odd;
}
public static Way createSingle(int positive, int negative) {
if (positive + negative == 0) return way[2][0];
if (positive + negative == 1) return way[1][1];
if (positive == 1 && negative == 1) return way[0][2];
if (positive + negative == 2) return way[2][0];
throw new RuntimeException();
}
public static Way createChain(int value, int positive, int negative) {
if (positive == 0 && negative == 0) return way[1][0];
if (positive + negative == 1) {
int res = positive == 1 ? value : (value ^ 1);
return res == 0 ? way[1][0] : way[0][1];
}
throw new RuntimeException();
}
public static Way createChain(int prevValue, int value, XnfEdge edge, int positive, int negative) {
int res = 0;
res ^= calc(prevValue, value, edge);
if (positive + negative == 0) {
} else if (positive + negative == 1) {
res ^= positive == 1 ? value : (value ^ 1);
} else {
throw new RuntimeException();
}
return res == 0 ? way[1][0] : way[0][1];
}
public static Way createSelfLoop(int value1, int value2) {
int even = (value1 == 0 ? 1 : 0) + (value2 == 0 ? 1 : 0);
int odd = (value1 == 1 ? 1 : 0) + (value2 == 1 ? 1 : 0);
return way[even][odd];
}
public static Way createLoop(int prevValue, int value, XnfEdge edge) {
return createChain(prevValue, value, edge, 0, 0);
}
public static Way createLoopEnd(int prevValue, int value, int nxtValue, XnfEdge prevEdge, XnfEdge nxtEdge) {
int res = calc(prevValue, value, prevEdge) ^ calc(value, nxtValue, nxtEdge);
return res == 0 ? way[1][0] : way[0][1];
}
public Way add(Way o) {
return new Way(
IntUtils.add(even, o.even),
IntUtils.add(odd, o.odd));
}
public Way mul(Way o) {
return new Way(
IntUtils.add(
IntUtils.mul(even, o.even),
IntUtils.mul(odd, o.odd)),
IntUtils.add(
IntUtils.mul(even, o.odd),
IntUtils.mul(odd, o.even)));
}
private static int calc(int prevValue, int value, XnfEdge edge) {
return (edge.fromNeg ? prevValue ^ 1 : prevValue) | (edge.toNeg ? value ^ 1 : value);
}
}
static class QuickScanner {
private static final int BUFFER_SIZE = 1024;
private InputStream stream;
private byte[] buffer;
private int currentPostion;
private int numberOfChars;
public QuickScanner(InputStream stream) {
this.stream = stream;
this.buffer = new byte[BUFFER_SIZE];
this.currentPostion = 0;
this.numberOfChars = 0;
}
public int nextInt() {
int c = nextNonSpaceChar();
boolean positive = true;
if (c == '-') {
positive = false;
c = nextChar();
}
int res = 0;
do {
if (c < '0' || '9' < c) throw new RuntimeException();
res = res * 10 + c - '0';
c = nextChar();
} while (!isSpaceChar(c));
return positive ? res : -res;
}
public int nextNonSpaceChar() {
int res = nextChar();
for (; isSpaceChar(res) || res < 0; res = nextChar()) ;
return res;
}
public int nextChar() {
if (numberOfChars == -1) {
throw new RuntimeException();
}
if (currentPostion >= numberOfChars) {
currentPostion = 0;
try {
numberOfChars = stream.read(buffer);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (numberOfChars <= 0) {
return -1;
}
}
return buffer[currentPostion++];
}
public boolean isSpaceChar(int c) {
return c == ' '
|| c == '\n'
|| c == '\r'
|| c == '\t'
|| c < 0;
}
}
static class XnfEdge extends BidirectionalGraphEdge {
final boolean fromNeg;
final boolean toNeg;
public XnfEdge(int fromIdx, int toIdx, boolean fromNeg, boolean toNeg) {
super(fromIdx, toIdx);
this.fromNeg = fromNeg;
this.toNeg = toNeg;
}
}
}
| Java | ["6 7\n2 4 -2\n2 6 3\n2 -7 1\n2 -5 1\n2 3 6\n2 -2 -5", "8 10\n1 -5\n2 4 -6\n2 -2 -6\n2 -7 9\n2 10 -1\n2 3 -1\n2 -8 9\n2 5 8", "2 3\n2 1 1\n2 -3 3"] | 2 seconds | ["48", "544", "4"] | NoteThe equation in the first sample is:The equation in the second sample is:The equation in the third sample is: | Java 8 | standard input | [
"dp",
"implementation",
"graphs",
"math"
] | e8e5338de3ff4a7c5e60d4507217465e | The first line of input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of clauses and the number of variables respectively. The next n lines contain the formula. The i-th of them starts with an integer ki — the number of literals in the i-th clause. It is followed by ki non-zero integers ai, 1, ..., ai, ki. If ai, j > 0 then vi, j is xai, j otherwise it's negation of x - ai, j (1 ≤ ki ≤ 2, - m ≤ ai, j ≤ m, ai, j ≠ 0). | 2,900 | Print the answer modulo 1 000 000 007 (109 + 7) in one line. | standard output | |
PASSED | 9d6f2b73b6fc44e4696b56ab6db10192 | train_004.jsonl | 1470578700 | Natalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form:Where represents logical OR and represents logical exclusive OR (XOR), and vi, j are some boolean variables or their negations. Natalia calls the left side of the equation a XNF formula. Each statement in brackets is called a clause, and vi, j are called literals.In the equation Natalia has, the left side is actually a 2-XNF-2 containing variables x1, x2, ..., xm and their negations. An XNF formula is 2-XNF-2 if: For each 1 ≤ i ≤ n, ki ≤ 2, i.e. the size of each clause doesn't exceed two. Each variable occurs in the formula at most two times (with negation and without negation in total). Please note that it's possible that a variable occurs twice but its negation doesn't occur in any clause (or vice versa). Natalia is given a formula of m variables, consisting of n clauses. Please, make sure to check the samples in order to properly understand how the formula looks like.Natalia is more into fight than theory, so she asked you to tell her the number of answers to this equation. More precisely, you need to find the number of ways to set x1, ..., xm with true and false (out of total of 2m ways) so that the equation is satisfied. Since this number can be extremely large, you need to print the answer modulo 109 + 7.Please, note that some variable may appear twice in one clause, or not appear in the equation at all (but still, setting it to false or true gives different ways to set variables). | 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.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 Jialin Ouyang (Jialin.Ouyang@gmail.com)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
QuickWriter out = new QuickWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int n;
int m;
int[] singlePositive;
int[] singleNegative;
boolean[] visited;
BidirectionalGraph<XnfEdge> graph;
public void solve(int testNumber, QuickScanner in, QuickWriter out) {
m = in.nextInt();
n = in.nextInt();
graph = new BidirectionalGraph<>(n, m);
graph.init(n);
singlePositive = new int[n];
singleNegative = new int[n];
visited = new boolean[n];
for (int i = 0; i < m; ++i) {
if (in.nextInt() == 1) {
int x = in.nextInt();
if (x > 0) {
++singlePositive[x - 1];
} else {
++singleNegative[-x - 1];
}
} else {
int x = in.nextInt();
int y = in.nextInt();
graph.add(
new XnfEdge(Math.abs(x) - 1, Math.abs(y) - 1, x < 0, y < 0),
new XnfEdge(Math.abs(y) - 1, Math.abs(x) - 1, y < 0, x < 0));
}
}
Way res = Way.way[1][0];
// Single
for (int i = 0; i < n; ++i)
if (graph.outDegree[i] == 0) {
visited[i] = true;
res = res.mul(Way.createSingle(singlePositive[i], singleNegative[i]));
}
// Chain
for (int i = 0; i < n; ++i)
if (!visited[i] && graph.outDegree[i] == 1) {
res = res.mul(dfsChain(i, null, null));
}
// Self loop
for (int i = 0; i < n; ++i)
if (!visited[i] && graph.lastEdge(i).toIdx == i) {
visited[i] = true;
XnfEdge edge = graph.lastEdge(i);
res = res.mul(Way.createSelfLoop(
(edge.fromNeg ? 1 : 0) | (edge.toNeg ? 1 : 0),
(edge.fromNeg ? 0 : 1) | (edge.toNeg ? 0 : 1)));
}
// Loop
for (int i = 0; i < n; ++i)
if (!visited[i]) {
res = res.mul(dfsLoop(i, null, null));
}
out.println(res.odd);
}
Way dfsChain(int u, Way[] ways, XnfEdge prevEdge) {
visited[u] = true;
Way[] nxtWays;
if (prevEdge == null) {
nxtWays = new Way[]{
Way.createChain(0, singlePositive[u], singleNegative[u]),
Way.createChain(1, singlePositive[u], singleNegative[u])};
} else {
nxtWays = new Way[]{
ways[0].mul(Way.createChain(0, 0, prevEdge, singlePositive[u], singleNegative[u])).add(
ways[1].mul(Way.createChain(1, 0, prevEdge, singlePositive[u], singleNegative[u]))),
ways[0].mul(Way.createChain(0, 1, prevEdge, singlePositive[u], singleNegative[u])).add(
ways[1].mul(Way.createChain(1, 1, prevEdge, singlePositive[u], singleNegative[u])))};
}
for (XnfEdge edge = graph.lastEdge(u); edge != null; edge = (XnfEdge) edge.next)
if (edge.reverse != prevEdge) {
return dfsChain(edge.toIdx, nxtWays, edge);
}
return nxtWays[0].add(nxtWays[1]);
}
Way dfsLoop(int u, Way[][] ways, XnfEdge prevEdge) {
visited[u] = true;
XnfEdge nxtEdge = null;
for (XnfEdge edge = graph.lastEdge(u); edge != null; edge = (XnfEdge) edge.next)
if (edge.reverse != prevEdge) {
nxtEdge = edge;
break;
}
if (prevEdge == null) {
return dfsLoop(
nxtEdge.toIdx,
new Way[][]{
{Way.way[1][0], Way.way[0][0]},
{Way.way[0][0], Way.way[1][0]}},
nxtEdge);
}
Way[][] nxtWays = new Way[][]{{Way.way[0][0], Way.way[0][0]}, {Way.way[0][0], Way.way[0][0]}};
if (!visited[nxtEdge.toIdx]) {
for (int start = 0; start < 2; ++start) {
for (int prevValue = 0; prevValue < 2; ++prevValue) {
for (int value = 0; value < 2; ++value) {
nxtWays[start][value] = nxtWays[start][value].add(
ways[start][prevValue].mul(Way.createLoop(prevValue, value, prevEdge)));
}
}
}
return dfsLoop(nxtEdge.toIdx, nxtWays, nxtEdge);
}
Way res = Way.way[0][0];
for (int start = 0; start < 2; ++start) {
for (int prevValue = 0; prevValue < 2; ++prevValue) {
for (int value = 0; value < 2; ++value) {
res = res.add(ways[start][prevValue].mul(Way.createLoopEnd(prevValue, value, start, prevEdge, nxtEdge)));
}
}
}
return res;
}
}
static class BidirectionalGraph<EDGE extends BidirectionalGraphEdge> extends DirectedGraph<EDGE> {
public BidirectionalGraph(int vertexCapacity, int edgeCapacity) {
super(vertexCapacity, edgeCapacity << 1);
}
public void add(EDGE edge, EDGE reverseEdge) {
add(edge);
add(reverseEdge);
edge.reverse = reverseEdge;
reverseEdge.reverse = edge;
}
}
static class BidirectionalGraphEdge extends DirectedGraphEdge {
public BidirectionalGraphEdge reverse;
public BidirectionalGraphEdge(int fromIdx, int toIdx) {
super(fromIdx, toIdx);
}
}
static class Way {
public static final Way[][] way;
final int even;
final int odd;
static {
way = new Way[3][3];
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j) {
way[i][j] = new Way(i, j);
}
}
public Way() {
this(0, 0);
}
private Way(int even, int odd) {
this.even = even;
this.odd = odd;
}
public static Way createSingle(int positive, int negative) {
if (positive + negative == 0) return way[2][0];
if (positive + negative == 1) return way[1][1];
if (positive == 1 && negative == 1) return way[0][2];
if (positive + negative == 2) return way[2][0];
throw new RuntimeException();
}
public static Way createChain(int value, int positive, int negative) {
if (positive == 0 && negative == 0) return way[1][0];
if (positive + negative == 1) {
int res = positive == 1 ? value : (value ^ 1);
return res == 0 ? way[1][0] : way[0][1];
}
throw new RuntimeException();
}
public static Way createChain(int prevValue, int value, XnfEdge edge, int positive, int negative) {
int res = 0;
res ^= calc(prevValue, value, edge);
if (positive + negative == 0) {
} else if (positive + negative == 1) {
res ^= positive == 1 ? value : (value ^ 1);
} else {
throw new RuntimeException();
}
return res == 0 ? way[1][0] : way[0][1];
}
public static Way createSelfLoop(int value1, int value2) {
int even = (value1 == 0 ? 1 : 0) + (value2 == 0 ? 1 : 0);
int odd = (value1 == 1 ? 1 : 0) + (value2 == 1 ? 1 : 0);
return way[even][odd];
}
public static Way createLoop(int prevValue, int value, XnfEdge edge) {
return createChain(prevValue, value, edge, 0, 0);
}
public static Way createLoopEnd(int prevValue, int value, int nxtValue, XnfEdge prevEdge, XnfEdge nxtEdge) {
int res = calc(prevValue, value, prevEdge) ^ calc(value, nxtValue, nxtEdge);
return res == 0 ? way[1][0] : way[0][1];
}
public Way add(Way o) {
return new Way(
IntUtils.add(even, o.even),
IntUtils.add(odd, o.odd));
}
public Way mul(Way o) {
return new Way(
IntUtils.add(
IntUtils.mul(even, o.even),
IntUtils.mul(odd, o.odd)),
IntUtils.add(
IntUtils.mul(even, o.odd),
IntUtils.mul(odd, o.even)));
}
private static int calc(int prevValue, int value, XnfEdge edge) {
return (edge.fromNeg ? prevValue ^ 1 : prevValue) | (edge.toNeg ? value ^ 1 : value);
}
}
static class IntUtils {
private static final int MOD = 1000000007;
public static int add(int a, int b) {
return add(a, b, MOD);
}
public static int add(int a, int b, int mod) {
a += b;
return a >= mod ? a - mod : a;
}
public static int mul(int a, int b) {
return mul(a, b, MOD);
}
public static int mul(int a, int b, int mod) {
return a > 0
? (
b < mod / a
? a * b
: (int) ((long) a * b % mod))
: 0;
}
}
static class DirectedGraphEdge {
public int fromIdx;
public int toIdx;
public DirectedGraphEdge next;
public DirectedGraphEdge nextIncoming;
public DirectedGraphEdge(int fromIdx, int toIdx) {
this.fromIdx = fromIdx;
this.toIdx = toIdx;
}
}
static class QuickWriter {
private final PrintWriter writer;
public QuickWriter(OutputStream outputStream) {
this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public QuickWriter(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.print('\n');
}
public void close() {
writer.close();
}
}
static class DirectedGraph<EDGE extends DirectedGraphEdge> {
public int vertexCnt;
public List<EDGE> edges;
public int[] inDegree;
public int[] outDegree;
private List<EDGE> lastEdge;
private List<EDGE> lastIncomingEdge;
public DirectedGraph(int vertexCapacity, int edgeCapacity) {
edges = new ArrayList<>(edgeCapacity);
lastEdge = new ArrayList<>(vertexCapacity);
lastIncomingEdge = new ArrayList<>(vertexCapacity);
inDegree = new int[vertexCapacity];
outDegree = new int[vertexCapacity];
}
public void init(int vertexCnt) {
this.vertexCnt = vertexCnt;
edges.clear();
lastEdge.clear();
lastIncomingEdge.clear();
Arrays.fill(inDegree, 0, vertexCnt, 0);
Arrays.fill(outDegree, 0, vertexCnt, 0);
for (int i = 0; i < vertexCnt; ++i) {
lastEdge.add(null);
lastIncomingEdge.add(null);
}
}
public void add(EDGE edge) {
edges.add(edge);
int fromIdx = edge.fromIdx;
int toIdx = edge.toIdx;
edge.next = lastEdge.get(fromIdx);
lastEdge.set(fromIdx, edge);
edge.nextIncoming = lastIncomingEdge.get(toIdx);
lastIncomingEdge.set(toIdx, edge);
++inDegree[toIdx];
++outDegree[fromIdx];
}
public EDGE lastEdge(int vertexIdx) {
return lastEdge.get(vertexIdx);
}
}
static class QuickScanner {
private static final int BUFFER_SIZE = 1024;
private InputStream stream;
private byte[] buffer;
private int currentPostion;
private int numberOfChars;
public QuickScanner(InputStream stream) {
this.stream = stream;
this.buffer = new byte[BUFFER_SIZE];
this.currentPostion = 0;
this.numberOfChars = 0;
}
public int nextInt() {
int c = nextNonSpaceChar();
boolean positive = true;
if (c == '-') {
positive = false;
c = nextChar();
}
int res = 0;
do {
if (c < '0' || '9' < c) throw new RuntimeException();
res = res * 10 + c - '0';
c = nextChar();
} while (!isSpaceChar(c));
return positive ? res : -res;
}
public int nextNonSpaceChar() {
int res = nextChar();
for (; isSpaceChar(res) || res < 0; res = nextChar()) ;
return res;
}
public int nextChar() {
if (numberOfChars == -1) {
throw new RuntimeException();
}
if (currentPostion >= numberOfChars) {
currentPostion = 0;
try {
numberOfChars = stream.read(buffer);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (numberOfChars <= 0) {
return -1;
}
}
return buffer[currentPostion++];
}
public boolean isSpaceChar(int c) {
return c == ' '
|| c == '\n'
|| c == '\r'
|| c == '\t'
|| c < 0;
}
}
static class XnfEdge extends BidirectionalGraphEdge {
final boolean fromNeg;
final boolean toNeg;
public XnfEdge(int fromIdx, int toIdx, boolean fromNeg, boolean toNeg) {
super(fromIdx, toIdx);
this.fromNeg = fromNeg;
this.toNeg = toNeg;
}
}
}
| Java | ["6 7\n2 4 -2\n2 6 3\n2 -7 1\n2 -5 1\n2 3 6\n2 -2 -5", "8 10\n1 -5\n2 4 -6\n2 -2 -6\n2 -7 9\n2 10 -1\n2 3 -1\n2 -8 9\n2 5 8", "2 3\n2 1 1\n2 -3 3"] | 2 seconds | ["48", "544", "4"] | NoteThe equation in the first sample is:The equation in the second sample is:The equation in the third sample is: | Java 8 | standard input | [
"dp",
"implementation",
"graphs",
"math"
] | e8e5338de3ff4a7c5e60d4507217465e | The first line of input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of clauses and the number of variables respectively. The next n lines contain the formula. The i-th of them starts with an integer ki — the number of literals in the i-th clause. It is followed by ki non-zero integers ai, 1, ..., ai, ki. If ai, j > 0 then vi, j is xai, j otherwise it's negation of x - ai, j (1 ≤ ki ≤ 2, - m ≤ ai, j ≤ m, ai, j ≠ 0). | 2,900 | Print the answer modulo 1 000 000 007 (109 + 7) in one line. | standard output | |
PASSED | 407a6f403ca828092afb66e86f52937d | train_004.jsonl | 1470578700 | Natalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form:Where represents logical OR and represents logical exclusive OR (XOR), and vi, j are some boolean variables or their negations. Natalia calls the left side of the equation a XNF formula. Each statement in brackets is called a clause, and vi, j are called literals.In the equation Natalia has, the left side is actually a 2-XNF-2 containing variables x1, x2, ..., xm and their negations. An XNF formula is 2-XNF-2 if: For each 1 ≤ i ≤ n, ki ≤ 2, i.e. the size of each clause doesn't exceed two. Each variable occurs in the formula at most two times (with negation and without negation in total). Please note that it's possible that a variable occurs twice but its negation doesn't occur in any clause (or vice versa). Natalia is given a formula of m variables, consisting of n clauses. Please, make sure to check the samples in order to properly understand how the formula looks like.Natalia is more into fight than theory, so she asked you to tell her the number of answers to this equation. More precisely, you need to find the number of ways to set x1, ..., xm with true and false (out of total of 2m ways) so that the equation is satisfied. Since this number can be extremely large, you need to print the answer modulo 109 + 7.Please, note that some variable may appear twice in one clause, or not appear in the equation at all (but still, setting it to false or true gives different ways to set variables). | 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.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 Jialin Ouyang (Jialin.Ouyang@gmail.com)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
QuickWriter out = new QuickWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int n;
int m;
int[] singlePositive;
int[] singleNegative;
boolean[] visited;
BidirectionalGraph<XnfEdge> graph;
public void solve(int testNumber, QuickScanner in, QuickWriter out) {
m = in.nextInt();
n = in.nextInt();
graph = new BidirectionalGraph<>(n, m);
graph.init(n);
singlePositive = new int[n];
singleNegative = new int[n];
visited = new boolean[n];
for (int i = 0; i < m; ++i) {
if (in.nextInt() == 1) {
int x = in.nextInt();
if (x > 0) {
++singlePositive[x - 1];
} else {
++singleNegative[-x - 1];
}
} else {
int x = in.nextInt();
int y = in.nextInt();
graph.add(
new XnfEdge(Math.abs(x) - 1, Math.abs(y) - 1, x < 0, y < 0),
new XnfEdge(Math.abs(y) - 1, Math.abs(x) - 1, y < 0, x < 0));
}
}
Way res = Way.way[1][0];
// Single
for (int i = 0; i < n; ++i)
if (graph.outDegree[i] == 0) {
visited[i] = true;
res = res.mul(Way.createSingle(singlePositive[i], singleNegative[i]));
}
// Chain
for (int i = 0; i < n; ++i)
if (!visited[i] && graph.outDegree[i] == 1) {
res = res.mul(dfsChain(i, null, null));
}
// Self loop
for (int i = 0; i < n; ++i)
if (!visited[i] && graph.lastEdge(i).toIdx == i) {
visited[i] = true;
XnfEdge edge = graph.lastEdge(i);
res = res.mul(Way.createSelfLoop(
(edge.fromNeg ? 1 : 0) | (edge.toNeg ? 1 : 0),
(edge.fromNeg ? 0 : 1) | (edge.toNeg ? 0 : 1)));
}
// Loop
for (int i = 0; i < n; ++i)
if (!visited[i]) {
res = res.mul(dfsLoop(i, null, null));
}
out.println(res.odd);
}
Way dfsChain(int u, Way[] ways, XnfEdge prevEdge) {
visited[u] = true;
Way[] nxtWays;
if (prevEdge == null) {
nxtWays = new Way[]{
Way.createChain(0, singlePositive[u], singleNegative[u]),
Way.createChain(1, singlePositive[u], singleNegative[u])};
} else {
nxtWays = new Way[]{
ways[0].mul(Way.createChain(0, 0, prevEdge, singlePositive[u], singleNegative[u])).add(
ways[1].mul(Way.createChain(1, 0, prevEdge, singlePositive[u], singleNegative[u]))),
ways[0].mul(Way.createChain(0, 1, prevEdge, singlePositive[u], singleNegative[u])).add(
ways[1].mul(Way.createChain(1, 1, prevEdge, singlePositive[u], singleNegative[u])))};
}
for (XnfEdge edge = graph.lastEdge(u); edge != null; edge = (XnfEdge) edge.next)
if (edge.reverse != prevEdge) {
return dfsChain(edge.toIdx, nxtWays, edge);
}
return nxtWays[0].add(nxtWays[1]);
}
Way dfsLoop(int u, Way[][] ways, XnfEdge prevEdge) {
visited[u] = true;
XnfEdge nxtEdge = null;
for (XnfEdge edge = graph.lastEdge(u); edge != null; edge = (XnfEdge) edge.next)
if (edge.reverse != prevEdge) {
nxtEdge = edge;
break;
}
if (prevEdge == null) {
return dfsLoop(
nxtEdge.toIdx,
new Way[][]{
{Way.way[1][0], Way.way[0][0]},
{Way.way[0][0], Way.way[1][0]}},
nxtEdge);
}
Way[][] nxtWays = new Way[][]{{Way.way[0][0], Way.way[0][0]}, {Way.way[0][0], Way.way[0][0]}};
if (!visited[nxtEdge.toIdx]) {
for (int start = 0; start < 2; ++start) {
for (int prevValue = 0; prevValue < 2; ++prevValue) {
for (int value = 0; value < 2; ++value) {
nxtWays[start][value] = nxtWays[start][value].add(
ways[start][prevValue].mul(Way.createLoop(prevValue, value, prevEdge)));
}
}
}
return dfsLoop(nxtEdge.toIdx, nxtWays, nxtEdge);
}
Way res = Way.way[0][0];
for (int start = 0; start < 2; ++start) {
for (int prevValue = 0; prevValue < 2; ++prevValue) {
for (int value = 0; value < 2; ++value) {
res = res.add(ways[start][prevValue].mul(Way.createLoopEnd(prevValue, value, start, prevEdge, nxtEdge)));
}
}
}
return res;
}
}
static class QuickScanner {
private static final int BUFFER_SIZE = 1024;
private InputStream stream;
private byte[] buffer;
private int currentPostion;
private int numberOfChars;
public QuickScanner(InputStream stream) {
this.stream = stream;
this.buffer = new byte[BUFFER_SIZE];
this.currentPostion = 0;
this.numberOfChars = 0;
}
public int nextInt() {
int c = nextNonSpaceChar();
boolean positive = true;
if (c == '-') {
positive = false;
c = nextChar();
}
int res = 0;
do {
if (c < '0' || '9' < c) throw new RuntimeException();
res = res * 10 + c - '0';
c = nextChar();
} while (!isSpaceChar(c));
return positive ? res : -res;
}
public int nextNonSpaceChar() {
int res = nextChar();
for (; isSpaceChar(res) || res < 0; res = nextChar()) ;
return res;
}
public int nextChar() {
if (numberOfChars == -1) {
throw new RuntimeException();
}
if (currentPostion >= numberOfChars) {
currentPostion = 0;
try {
numberOfChars = stream.read(buffer);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (numberOfChars <= 0) {
return -1;
}
}
return buffer[currentPostion++];
}
public boolean isSpaceChar(int c) {
return c == ' '
|| c == '\n'
|| c == '\r'
|| c == '\t'
|| c < 0;
}
}
static class XnfEdge extends BidirectionalGraphEdge {
final boolean fromNeg;
final boolean toNeg;
public XnfEdge(int fromIdx, int toIdx, boolean fromNeg, boolean toNeg) {
super(fromIdx, toIdx);
this.fromNeg = fromNeg;
this.toNeg = toNeg;
}
}
static class BidirectionalGraph<EDGE extends BidirectionalGraphEdge> extends DirectedGraph<EDGE> {
public BidirectionalGraph(int vertexCapacity, int edgeCapacity) {
super(vertexCapacity, edgeCapacity << 1);
}
public void add(EDGE edge, EDGE reverseEdge) {
add(edge);
add(reverseEdge);
edge.reverse = reverseEdge;
reverseEdge.reverse = edge;
}
}
static class BidirectionalGraphEdge extends DirectedGraphEdge {
public BidirectionalGraphEdge reverse;
public BidirectionalGraphEdge(int fromIdx, int toIdx) {
super(fromIdx, toIdx);
}
}
static class DirectedGraphEdge {
public int fromIdx;
public int toIdx;
public DirectedGraphEdge next;
public DirectedGraphEdge nextIncoming;
public DirectedGraphEdge(int fromIdx, int toIdx) {
this.fromIdx = fromIdx;
this.toIdx = toIdx;
}
}
static class Way {
public static final Way[][] way;
final int even;
final int odd;
static {
way = new Way[3][3];
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j) {
way[i][j] = new Way(i, j);
}
}
public Way() {
this(0, 0);
}
private Way(int even, int odd) {
this.even = even;
this.odd = odd;
}
public static Way createSingle(int positive, int negative) {
if (positive + negative == 0) return way[2][0];
if (positive + negative == 1) return way[1][1];
if (positive == 1 && negative == 1) return way[0][2];
if (positive + negative == 2) return way[2][0];
throw new RuntimeException();
}
public static Way createChain(int value, int positive, int negative) {
if (positive == 0 && negative == 0) return way[1][0];
if (positive + negative == 1) {
int res = positive == 1 ? value : (value ^ 1);
return res == 0 ? way[1][0] : way[0][1];
}
throw new RuntimeException();
}
public static Way createChain(int prevValue, int value, XnfEdge edge, int positive, int negative) {
int res = 0;
res ^= calc(prevValue, value, edge);
if (positive + negative == 0) {
} else if (positive + negative == 1) {
res ^= positive == 1 ? value : (value ^ 1);
} else {
throw new RuntimeException();
}
return res == 0 ? way[1][0] : way[0][1];
}
public static Way createSelfLoop(int value1, int value2) {
int even = (value1 == 0 ? 1 : 0) + (value2 == 0 ? 1 : 0);
int odd = (value1 == 1 ? 1 : 0) + (value2 == 1 ? 1 : 0);
return way[even][odd];
}
public static Way createLoop(int prevValue, int value, XnfEdge edge) {
return createChain(prevValue, value, edge, 0, 0);
}
public static Way createLoopEnd(int prevValue, int value, int nxtValue, XnfEdge prevEdge, XnfEdge nxtEdge) {
int res = calc(prevValue, value, prevEdge) ^ calc(value, nxtValue, nxtEdge);
return res == 0 ? way[1][0] : way[0][1];
}
public Way add(Way o) {
return new Way(
IntUtils.add(even, o.even),
IntUtils.add(odd, o.odd));
}
public Way mul(Way o) {
return new Way(
IntUtils.add(
IntUtils.mul(even, o.even),
IntUtils.mul(odd, o.odd)),
IntUtils.add(
IntUtils.mul(even, o.odd),
IntUtils.mul(odd, o.even)));
}
private static int calc(int prevValue, int value, XnfEdge edge) {
return (edge.fromNeg ? prevValue ^ 1 : prevValue) | (edge.toNeg ? value ^ 1 : value);
}
}
static class QuickWriter {
private final PrintWriter writer;
public QuickWriter(OutputStream outputStream) {
this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public QuickWriter(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.print('\n');
}
public void close() {
writer.close();
}
}
static class DirectedGraph<EDGE extends DirectedGraphEdge> {
public int vertexCnt;
public List<EDGE> edges;
public int[] inDegree;
public int[] outDegree;
private List<EDGE> lastEdge;
private List<EDGE> lastIncomingEdge;
public DirectedGraph(int vertexCapacity, int edgeCapacity) {
edges = new ArrayList<>(edgeCapacity);
lastEdge = new ArrayList<>(vertexCapacity);
lastIncomingEdge = new ArrayList<>(vertexCapacity);
inDegree = new int[vertexCapacity];
outDegree = new int[vertexCapacity];
}
public void init(int vertexCnt) {
this.vertexCnt = vertexCnt;
edges.clear();
lastEdge.clear();
lastIncomingEdge.clear();
Arrays.fill(inDegree, 0, vertexCnt, 0);
Arrays.fill(outDegree, 0, vertexCnt, 0);
for (int i = 0; i < vertexCnt; ++i) {
lastEdge.add(null);
lastIncomingEdge.add(null);
}
}
public void add(EDGE edge) {
edges.add(edge);
int fromIdx = edge.fromIdx;
int toIdx = edge.toIdx;
edge.next = lastEdge.get(fromIdx);
lastEdge.set(fromIdx, edge);
edge.nextIncoming = lastIncomingEdge.get(toIdx);
lastIncomingEdge.set(toIdx, edge);
++inDegree[toIdx];
++outDegree[fromIdx];
}
public EDGE lastEdge(int vertexIdx) {
return lastEdge.get(vertexIdx);
}
}
static class IntUtils {
private static final int MOD = 1000000007;
public static int add(int a, int b) {
return add(a, b, MOD);
}
public static int add(int a, int b, int mod) {
a += b;
return a >= mod ? a - mod : a;
}
public static int mul(int a, int b) {
return mul(a, b, MOD);
}
public static int mul(int a, int b, int mod) {
return a > 0
? (
b < mod / a
? a * b
: (int) ((long) a * b % mod))
: 0;
}
}
}
| Java | ["6 7\n2 4 -2\n2 6 3\n2 -7 1\n2 -5 1\n2 3 6\n2 -2 -5", "8 10\n1 -5\n2 4 -6\n2 -2 -6\n2 -7 9\n2 10 -1\n2 3 -1\n2 -8 9\n2 5 8", "2 3\n2 1 1\n2 -3 3"] | 2 seconds | ["48", "544", "4"] | NoteThe equation in the first sample is:The equation in the second sample is:The equation in the third sample is: | Java 8 | standard input | [
"dp",
"implementation",
"graphs",
"math"
] | e8e5338de3ff4a7c5e60d4507217465e | The first line of input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of clauses and the number of variables respectively. The next n lines contain the formula. The i-th of them starts with an integer ki — the number of literals in the i-th clause. It is followed by ki non-zero integers ai, 1, ..., ai, ki. If ai, j > 0 then vi, j is xai, j otherwise it's negation of x - ai, j (1 ≤ ki ≤ 2, - m ≤ ai, j ≤ m, ai, j ≠ 0). | 2,900 | Print the answer modulo 1 000 000 007 (109 + 7) in one line. | standard output | |
PASSED | d0da1ba90680c12271c7b256dd21754e | train_004.jsonl | 1470578700 | Natalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form:Where represents logical OR and represents logical exclusive OR (XOR), and vi, j are some boolean variables or their negations. Natalia calls the left side of the equation a XNF formula. Each statement in brackets is called a clause, and vi, j are called literals.In the equation Natalia has, the left side is actually a 2-XNF-2 containing variables x1, x2, ..., xm and their negations. An XNF formula is 2-XNF-2 if: For each 1 ≤ i ≤ n, ki ≤ 2, i.e. the size of each clause doesn't exceed two. Each variable occurs in the formula at most two times (with negation and without negation in total). Please note that it's possible that a variable occurs twice but its negation doesn't occur in any clause (or vice versa). Natalia is given a formula of m variables, consisting of n clauses. Please, make sure to check the samples in order to properly understand how the formula looks like.Natalia is more into fight than theory, so she asked you to tell her the number of answers to this equation. More precisely, you need to find the number of ways to set x1, ..., xm with true and false (out of total of 2m ways) so that the equation is satisfied. Since this number can be extremely large, you need to print the answer modulo 109 + 7.Please, note that some variable may appear twice in one clause, or not appear in the equation at all (but still, setting it to false or true gives different ways to set variables). | 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.util.Iterator;
import java.io.BufferedWriter;
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 Jialin Ouyang (Jialin.Ouyang@gmail.com)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
QuickWriter out = new QuickWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int n;
int m;
int[] singlePositive;
int[] singleNegative;
boolean[] visited;
BidirectionalGraph<XnfEdge> graph;
public void solve(int testNumber, QuickScanner in, QuickWriter out) {
m = in.nextInt();
n = in.nextInt();
graph = new BidirectionalGraph<>(n, m);
graph.init(n);
singlePositive = new int[n];
singleNegative = new int[n];
visited = new boolean[n];
for (int i = 0; i < m; ++i) {
if (in.nextInt() == 1) {
int x = in.nextInt();
if (x > 0) {
++singlePositive[x - 1];
} else {
++singleNegative[-x - 1];
}
} else {
int x = in.nextInt();
int y = in.nextInt();
graph.add(
new XnfEdge(Math.abs(x) - 1, Math.abs(y) - 1, x < 0, y < 0),
new XnfEdge(Math.abs(y) - 1, Math.abs(x) - 1, y < 0, x < 0));
}
}
Way res = Way.way[1][0];
// Single
for (int i = 0; i < n; ++i)
if (graph.outDegree[i] == 0) {
visited[i] = true;
res = res.mul(Way.createSingle(singlePositive[i], singleNegative[i]));
}
// Chain
for (int i = 0; i < n; ++i)
if (!visited[i] && graph.outDegree[i] == 1) {
res = res.mul(dfsChain(i, null, null));
}
// Self loop
for (int i = 0; i < n; ++i)
if (!visited[i] && graph.lastEdge.get(i).toIdx == i) {
visited[i] = true;
XnfEdge edge = graph.lastEdge.get(i);
res = res.mul(Way.createSelfLoop(
(edge.fromNeg ? 1 : 0) | (edge.toNeg ? 1 : 0),
(edge.fromNeg ? 0 : 1) | (edge.toNeg ? 0 : 1)));
}
// Loop
for (int i = 0; i < n; ++i)
if (!visited[i]) {
res = res.mul(dfsLoop(i, null, null));
}
out.println(res.odd);
}
Way dfsChain(int u, Way[] ways, XnfEdge prevEdge) {
visited[u] = true;
Way[] nxtWays;
if (prevEdge == null) {
nxtWays = new Way[]{
Way.createChain(0, singlePositive[u], singleNegative[u]),
Way.createChain(1, singlePositive[u], singleNegative[u])};
} else {
nxtWays = new Way[]{
ways[0].mul(Way.createChain(0, 0, prevEdge, singlePositive[u], singleNegative[u])).add(
ways[1].mul(Way.createChain(1, 0, prevEdge, singlePositive[u], singleNegative[u]))),
ways[0].mul(Way.createChain(0, 1, prevEdge, singlePositive[u], singleNegative[u])).add(
ways[1].mul(Way.createChain(1, 1, prevEdge, singlePositive[u], singleNegative[u])))};
}
for (XnfEdge edge : graph.edges(u))
if (edge.reverse != prevEdge) {
// for (XnfEdge edge = graph.lastEdge(u); edge != null; edge = (XnfEdge) edge.next) if (edge.reverse != prevEdge) {
return dfsChain(edge.toIdx, nxtWays, edge);
}
return nxtWays[0].add(nxtWays[1]);
}
Way dfsLoop(int u, Way[][] ways, XnfEdge prevEdge) {
visited[u] = true;
XnfEdge nxtEdge = null;
for (XnfEdge edge : graph.edges(u))
if (edge.reverse != prevEdge) {
// for (XnfEdge edge = graph.lastEdge(u); edge != null; edge = (XnfEdge) edge.next) if (edge.reverse != prevEdge) {
nxtEdge = edge;
break;
}
if (prevEdge == null) {
return dfsLoop(
nxtEdge.toIdx,
new Way[][]{
{Way.way[1][0], Way.way[0][0]},
{Way.way[0][0], Way.way[1][0]}},
nxtEdge);
}
Way[][] nxtWays = new Way[][]{{Way.way[0][0], Way.way[0][0]}, {Way.way[0][0], Way.way[0][0]}};
if (!visited[nxtEdge.toIdx]) {
for (int start = 0; start < 2; ++start) {
for (int prevValue = 0; prevValue < 2; ++prevValue) {
for (int value = 0; value < 2; ++value) {
nxtWays[start][value] = nxtWays[start][value].add(
ways[start][prevValue].mul(Way.createLoop(prevValue, value, prevEdge)));
}
}
}
return dfsLoop(nxtEdge.toIdx, nxtWays, nxtEdge);
}
Way res = Way.way[0][0];
for (int start = 0; start < 2; ++start) {
for (int prevValue = 0; prevValue < 2; ++prevValue) {
for (int value = 0; value < 2; ++value) {
res = res.add(ways[start][prevValue].mul(Way.createLoopEnd(prevValue, value, start, prevEdge, nxtEdge)));
}
}
}
return res;
}
}
static class QuickScanner {
private static final int BUFFER_SIZE = 1024;
private InputStream stream;
private byte[] buffer;
private int currentPostion;
private int numberOfChars;
public QuickScanner(InputStream stream) {
this.stream = stream;
this.buffer = new byte[BUFFER_SIZE];
this.currentPostion = 0;
this.numberOfChars = 0;
}
public int nextInt() {
int c = nextNonSpaceChar();
boolean positive = true;
if (c == '-') {
positive = false;
c = nextChar();
}
int res = 0;
do {
if (c < '0' || '9' < c) throw new RuntimeException();
res = res * 10 + c - '0';
c = nextChar();
} while (!isSpaceChar(c));
return positive ? res : -res;
}
public int nextNonSpaceChar() {
int res = nextChar();
for (; isSpaceChar(res) || res < 0; res = nextChar()) ;
return res;
}
public int nextChar() {
if (numberOfChars == -1) {
throw new RuntimeException();
}
if (currentPostion >= numberOfChars) {
currentPostion = 0;
try {
numberOfChars = stream.read(buffer);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (numberOfChars <= 0) {
return -1;
}
}
return buffer[currentPostion++];
}
public boolean isSpaceChar(int c) {
return c == ' '
|| c == '\n'
|| c == '\r'
|| c == '\t'
|| c < 0;
}
}
static class BidirectionalGraph<EDGE extends BidirectionalGraphEdge> extends DirectedGraph<EDGE> {
public BidirectionalGraph(int vertexCapacity, int edgeCapacity) {
super(vertexCapacity, edgeCapacity << 1);
}
public void add(EDGE edge, EDGE reverseEdge) {
add(edge);
add(reverseEdge);
edge.reverse = reverseEdge;
reverseEdge.reverse = edge;
}
}
static class BidirectionalGraphEdge extends DirectedGraphEdge {
public BidirectionalGraphEdge reverse;
public BidirectionalGraphEdge(int fromIdx, int toIdx) {
super(fromIdx, toIdx);
}
}
static class Way {
public static final Way[][] way;
final int even;
final int odd;
static {
way = new Way[3][3];
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j) {
way[i][j] = new Way(i, j);
}
}
public Way() {
this(0, 0);
}
private Way(int even, int odd) {
this.even = even;
this.odd = odd;
}
public static Way createSingle(int positive, int negative) {
if (positive + negative == 0) return way[2][0];
if (positive + negative == 1) return way[1][1];
if (positive == 1 && negative == 1) return way[0][2];
if (positive + negative == 2) return way[2][0];
throw new RuntimeException();
}
public static Way createChain(int value, int positive, int negative) {
if (positive == 0 && negative == 0) return way[1][0];
if (positive + negative == 1) {
int res = positive == 1 ? value : (value ^ 1);
return res == 0 ? way[1][0] : way[0][1];
}
throw new RuntimeException();
}
public static Way createChain(int prevValue, int value, XnfEdge edge, int positive, int negative) {
int res = 0;
res ^= calc(prevValue, value, edge);
if (positive + negative == 0) {
} else if (positive + negative == 1) {
res ^= positive == 1 ? value : (value ^ 1);
} else {
throw new RuntimeException();
}
return res == 0 ? way[1][0] : way[0][1];
}
public static Way createSelfLoop(int value1, int value2) {
int even = (value1 == 0 ? 1 : 0) + (value2 == 0 ? 1 : 0);
int odd = (value1 == 1 ? 1 : 0) + (value2 == 1 ? 1 : 0);
return way[even][odd];
}
public static Way createLoop(int prevValue, int value, XnfEdge edge) {
return createChain(prevValue, value, edge, 0, 0);
}
public static Way createLoopEnd(int prevValue, int value, int nxtValue, XnfEdge prevEdge, XnfEdge nxtEdge) {
int res = calc(prevValue, value, prevEdge) ^ calc(value, nxtValue, nxtEdge);
return res == 0 ? way[1][0] : way[0][1];
}
public Way add(Way o) {
return new Way(
IntUtils.add(even, o.even),
IntUtils.add(odd, o.odd));
}
public Way mul(Way o) {
return new Way(
IntUtils.add(
IntUtils.mul(even, o.even),
IntUtils.mul(odd, o.odd)),
IntUtils.add(
IntUtils.mul(even, o.odd),
IntUtils.mul(odd, o.even)));
}
private static int calc(int prevValue, int value, XnfEdge edge) {
return (edge.fromNeg ? prevValue ^ 1 : prevValue) | (edge.toNeg ? value ^ 1 : value);
}
}
static class DirectedGraphEdge {
public int fromIdx;
public int toIdx;
public DirectedGraphEdge next;
public DirectedGraphEdge nextIncoming;
public DirectedGraphEdge(int fromIdx, int toIdx) {
this.fromIdx = fromIdx;
this.toIdx = toIdx;
}
}
static class QuickWriter {
private final PrintWriter writer;
public QuickWriter(OutputStream outputStream) {
this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public QuickWriter(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.print('\n');
}
public void close() {
writer.close();
}
}
static class DirectedGraph<EDGE extends DirectedGraphEdge> {
public int vertexCnt;
public List<EDGE> edges;
public int[] inDegree;
public int[] outDegree;
public List<EDGE> lastEdge;
public List<EDGE> lastIncomingEdge;
public DirectedGraph(int vertexCapacity, int edgeCapacity) {
edges = new ArrayList<>(edgeCapacity);
lastEdge = new ArrayList<>(vertexCapacity);
lastIncomingEdge = new ArrayList<>(vertexCapacity);
inDegree = new int[vertexCapacity];
outDegree = new int[vertexCapacity];
}
public void init(int vertexCnt) {
this.vertexCnt = vertexCnt;
edges.clear();
lastEdge.clear();
lastIncomingEdge.clear();
Arrays.fill(inDegree, 0, vertexCnt, 0);
Arrays.fill(outDegree, 0, vertexCnt, 0);
for (int i = 0; i < vertexCnt; ++i) {
lastEdge.add(null);
lastIncomingEdge.add(null);
}
}
public void add(EDGE edge) {
edges.add(edge);
int fromIdx = edge.fromIdx;
int toIdx = edge.toIdx;
edge.next = lastEdge.get(fromIdx);
lastEdge.set(fromIdx, edge);
edge.nextIncoming = lastIncomingEdge.get(toIdx);
lastIncomingEdge.set(toIdx, edge);
++inDegree[toIdx];
++outDegree[fromIdx];
}
public Iterable<EDGE> edges(int vertexIdx) {
return () -> new Iterator<EDGE>() {
EDGE edge = lastEdge.get(vertexIdx);
public boolean hasNext() {
return edge != null;
}
public EDGE next() {
EDGE currentEdge = edge;
edge = (EDGE) edge.next;
return currentEdge;
}
};
}
}
static class IntUtils {
private static final int MOD = 1000000007;
public static int add(int a, int b) {
return add(a, b, MOD);
}
public static int add(int a, int b, int mod) {
a += b;
return a >= mod ? a - mod : a;
}
public static int mul(int a, int b) {
return mul(a, b, MOD);
}
public static int mul(int a, int b, int mod) {
return a > 0
? (
b < mod / a
? a * b
: (int) ((long) a * b % mod))
: 0;
}
}
static class XnfEdge extends BidirectionalGraphEdge {
final boolean fromNeg;
final boolean toNeg;
public XnfEdge(int fromIdx, int toIdx, boolean fromNeg, boolean toNeg) {
super(fromIdx, toIdx);
this.fromNeg = fromNeg;
this.toNeg = toNeg;
}
}
}
| Java | ["6 7\n2 4 -2\n2 6 3\n2 -7 1\n2 -5 1\n2 3 6\n2 -2 -5", "8 10\n1 -5\n2 4 -6\n2 -2 -6\n2 -7 9\n2 10 -1\n2 3 -1\n2 -8 9\n2 5 8", "2 3\n2 1 1\n2 -3 3"] | 2 seconds | ["48", "544", "4"] | NoteThe equation in the first sample is:The equation in the second sample is:The equation in the third sample is: | Java 8 | standard input | [
"dp",
"implementation",
"graphs",
"math"
] | e8e5338de3ff4a7c5e60d4507217465e | The first line of input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of clauses and the number of variables respectively. The next n lines contain the formula. The i-th of them starts with an integer ki — the number of literals in the i-th clause. It is followed by ki non-zero integers ai, 1, ..., ai, ki. If ai, j > 0 then vi, j is xai, j otherwise it's negation of x - ai, j (1 ≤ ki ≤ 2, - m ≤ ai, j ≤ m, ai, j ≠ 0). | 2,900 | Print the answer modulo 1 000 000 007 (109 + 7) in one line. | standard output | |
PASSED | c8828e30fc8ab2d927e1ed8aa7b96aad | train_004.jsonl | 1470578700 | Natalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form:Where represents logical OR and represents logical exclusive OR (XOR), and vi, j are some boolean variables or their negations. Natalia calls the left side of the equation a XNF formula. Each statement in brackets is called a clause, and vi, j are called literals.In the equation Natalia has, the left side is actually a 2-XNF-2 containing variables x1, x2, ..., xm and their negations. An XNF formula is 2-XNF-2 if: For each 1 ≤ i ≤ n, ki ≤ 2, i.e. the size of each clause doesn't exceed two. Each variable occurs in the formula at most two times (with negation and without negation in total). Please note that it's possible that a variable occurs twice but its negation doesn't occur in any clause (or vice versa). Natalia is given a formula of m variables, consisting of n clauses. Please, make sure to check the samples in order to properly understand how the formula looks like.Natalia is more into fight than theory, so she asked you to tell her the number of answers to this equation. More precisely, you need to find the number of ways to set x1, ..., xm with true and false (out of total of 2m ways) so that the equation is satisfied. Since this number can be extremely large, you need to print the answer modulo 109 + 7.Please, note that some variable may appear twice in one clause, or not appear in the equation at all (but still, setting it to false or true gives different ways to set variables). | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.ArrayList;
import java.io.OutputStreamWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.List;
import java.io.Closeable;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
CBlackWidow solver = new CBlackWidow();
solver.solve(1, in, out);
out.close();
}
}
static class CBlackWidow {
List<Node> dq;
long[] sum;
int mod = (int) 1e9 + 7;
public void solve(int testNumber, FastInput in, FastOutput out) {
int m = in.readInt();
int n = in.readInt();
IntegerArrayList[] values = new IntegerArrayList[n];
IntegerArrayList[] occurs = new IntegerArrayList[n];
for (int i = 0; i < n; i++) {
occurs[i] = new IntegerArrayList(2);
values[i] = new IntegerArrayList(2);
}
for (int i = 0; i < m; i++) {
int k = in.readInt();
for (int j = 0; j < k; j++) {
int x = in.readInt();
int id = Math.abs(x) - 1;
occurs[id].add(i);
values[id].add(x);
}
}
Node[] nodes = new Node[m];
for (int i = 0; i < m; i++) {
nodes[i] = new Node();
nodes[i].id = i;
}
long extra = 1;
for (int i = 0; i < n; i++) {
IntegerArrayList list = occurs[i];
if (list.size() == 2) {
int a = list.get(0);
int b = list.get(1);
addEdge(nodes[a], nodes[b], values[i].get(0) == values[i].get(1) ? 0 : 1);
continue;
}
if (list.size() == 1) {
int a = list.get(0);
nodes[a].virtual++;
continue;
}
if (list.size() == 0) {
extra = extra * 2 % mod;
}
}
dq = new ArrayList<>();
List<long[]> data = new ArrayList<>();
for (Node node : nodes) {
if (node.visited) {
continue;
}
dq.clear();
Node leaf = findLeaf(node, null);
find(leaf, null);
Node first = dq.get(0);
Node tail = dq.get(dq.size() - 1);
sum = new long[2];
if (tail.next != null) {
//circle
if (tail.next.xor == 0) {
first.light = tail.light = 1;
bf(0);
first.light = tail.light = 0;
bf(0);
} else {
first.light = 1;
bf(0);
first.light = 0;
tail.light = 1;
bf(0);
}
first.light = tail.light = 0;
} else {
bf(0);
}
data.add(sum);
}
long[] last = new long[]{1, 0};
long[] next = new long[2];
for (long[] d : data) {
Arrays.fill(next, 0);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
next[i ^ j] += last[i] * d[j] % mod;
}
}
for (int i = 0; i < 2; i++) {
next[i] %= mod;
}
long[] tmp = last;
last = next;
next = tmp;
}
long ans = last[1] * extra % mod;
out.println(ans);
}
public void bf(int i) {
if (i >= dq.size()) {
add(sum, dp(), 0);
return;
}
Node node = dq.get(i);
int nodeVirtual = node.virtual;
int light = node.light;
if (node.virtual > 0) {
node.virtual--;
bf(i);
node.light = 1;
bf(i);
} else {
bf(i + 1);
}
node.virtual = nodeVirtual;
node.light = light;
}
public long[] dp() {
long[][] last = new long[2][2];
long[][] next = new long[2][2];
Node first = dq.get(0);
last[first.light][first.light] = 1;
for (int i = 1; i < dq.size(); i++) {
Node node = dq.get(i);
SequenceUtils.deepFill(next, 0L);
Edge e = dq.get(i - 1).next;
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
long way = last[j][k];
if (way == 0) {
continue;
}
if (e.xor == 1) {
for (int t = 0; t < 2; t++) {
int diff = 0;
if (t == 0 && k == 0) {
diff = 1;
}
int go = Math.max(t, node.light);
diff ^= go;
next[j ^ diff][go] += way;
}
} else {
for (int t = 0; t < 2; t++) {
int diff = 0;
if (t == 0) {
diff = node.light;
} else {
if (k == 0) {
diff ^= 1;
}
diff ^= 1;
}
int go = Math.max(t, node.light);
next[j ^ diff][go] += way;
}
}
}
}
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
next[j][k] %= mod;
}
}
long[][] tmp = last;
last = next;
next = tmp;
}
long[] ans = new long[2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
ans[i] += last[i][j];
ans[i] %= mod;
}
}
return ans;
}
public Node findLeaf(Node root, Edge p) {
if (root.tag) {
return root;
}
root.tag = true;
for (Edge e : root.adj) {
if (e == p) {
continue;
}
return findLeaf(e.other(root), e);
}
return root;
}
public void find(Node root, Edge p) {
if (root.visited) {
return;
}
root.visited = true;
dq.add(root);
for (Edge e : root.adj) {
if (e == p) {
continue;
}
root.next = e;
find(e.other(root), e);
return;
}
}
public void addEdge(Node a, Node b, int xor) {
Edge e = new Edge();
e.a = a;
e.b = b;
e.xor = xor;
a.adj.add(e);
b.adj.add(e);
}
public void add(long[] a, long[] b, int xor) {
for (int i = 0; i < 2; i++) {
a[i] += b[i ^ xor];
}
}
}
static class SequenceUtils {
public static void deepFill(Object array, long val) {
if (!array.getClass().isArray()) {
throw new IllegalArgumentException();
}
if (array instanceof long[]) {
long[] longArray = (long[]) array;
Arrays.fill(longArray, val);
} else {
Object[] objArray = (Object[]) array;
for (Object obj : objArray) {
deepFill(obj, val);
}
}
}
public static boolean equal(int[] a, int al, int ar, int[] b, int bl, int br) {
if ((ar - al) != (br - bl)) {
return false;
}
for (int i = al, j = bl; i <= ar; i++, j++) {
if (a[i] != b[j]) {
return false;
}
}
return true;
}
}
static class IntegerArrayList implements Cloneable {
private int size;
private int cap;
private int[] data;
private static final int[] EMPTY = new int[0];
public IntegerArrayList(int cap) {
this.cap = cap;
if (cap == 0) {
data = EMPTY;
} else {
data = new int[cap];
}
}
public IntegerArrayList(IntegerArrayList list) {
this.size = list.size;
this.cap = list.cap;
this.data = Arrays.copyOf(list.data, size);
}
public IntegerArrayList() {
this(0);
}
public void ensureSpace(int req) {
if (req > cap) {
while (cap < req) {
cap = Math.max(cap + 10, 2 * cap);
}
data = Arrays.copyOf(data, cap);
}
}
private void checkRange(int i) {
if (i < 0 || i >= size) {
throw new ArrayIndexOutOfBoundsException();
}
}
public int get(int i) {
checkRange(i);
return data[i];
}
public void add(int x) {
ensureSpace(size + 1);
data[size++] = x;
}
public void addAll(int[] x, int offset, int len) {
ensureSpace(size + len);
System.arraycopy(x, offset, data, size, len);
size += len;
}
public void addAll(IntegerArrayList list) {
addAll(list.data, 0, list.size);
}
public int size() {
return size;
}
public int[] toArray() {
return Arrays.copyOf(data, size);
}
public String toString() {
return Arrays.toString(toArray());
}
public boolean equals(Object obj) {
if (!(obj instanceof IntegerArrayList)) {
return false;
}
IntegerArrayList other = (IntegerArrayList) obj;
return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1);
}
public int hashCode() {
int h = 1;
for (int i = 0; i < size; i++) {
h = h * 31 + Integer.hashCode(data[i]);
}
return h;
}
public IntegerArrayList clone() {
IntegerArrayList ans = new IntegerArrayList();
ans.addAll(this);
return ans;
}
}
static class Edge {
Node a;
Node b;
int xor;
Node other(Node x) {
return a == x ? b : a;
}
}
static class Node {
List<Edge> adj = new ArrayList<>();
int virtual;
boolean visited;
boolean tag;
int light;
Edge next;
int id;
public String toString() {
return "" + (id + 1);
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
public FastOutput append(CharSequence csq) {
cache.append(csq);
return this;
}
public FastOutput append(CharSequence csq, int start, int end) {
cache.append(csq, start, end);
return this;
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput append(char c) {
cache.append(c);
return this;
}
public FastOutput append(long c) {
cache.append(c);
return this;
}
public FastOutput println(long c) {
return append(c).println();
}
public FastOutput println() {
cache.append(System.lineSeparator());
return this;
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
}
}
| Java | ["6 7\n2 4 -2\n2 6 3\n2 -7 1\n2 -5 1\n2 3 6\n2 -2 -5", "8 10\n1 -5\n2 4 -6\n2 -2 -6\n2 -7 9\n2 10 -1\n2 3 -1\n2 -8 9\n2 5 8", "2 3\n2 1 1\n2 -3 3"] | 2 seconds | ["48", "544", "4"] | NoteThe equation in the first sample is:The equation in the second sample is:The equation in the third sample is: | Java 8 | standard input | [
"dp",
"implementation",
"graphs",
"math"
] | e8e5338de3ff4a7c5e60d4507217465e | The first line of input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of clauses and the number of variables respectively. The next n lines contain the formula. The i-th of them starts with an integer ki — the number of literals in the i-th clause. It is followed by ki non-zero integers ai, 1, ..., ai, ki. If ai, j > 0 then vi, j is xai, j otherwise it's negation of x - ai, j (1 ≤ ki ≤ 2, - m ≤ ai, j ≤ m, ai, j ≠ 0). | 2,900 | Print the answer modulo 1 000 000 007 (109 + 7) in one line. | standard output | |
PASSED | 558e9fcbc9ecf420b6124ce783a9167d | train_004.jsonl | 1470578700 | Natalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form:Where represents logical OR and represents logical exclusive OR (XOR), and vi, j are some boolean variables or their negations. Natalia calls the left side of the equation a XNF formula. Each statement in brackets is called a clause, and vi, j are called literals.In the equation Natalia has, the left side is actually a 2-XNF-2 containing variables x1, x2, ..., xm and their negations. An XNF formula is 2-XNF-2 if: For each 1 ≤ i ≤ n, ki ≤ 2, i.e. the size of each clause doesn't exceed two. Each variable occurs in the formula at most two times (with negation and without negation in total). Please note that it's possible that a variable occurs twice but its negation doesn't occur in any clause (or vice versa). Natalia is given a formula of m variables, consisting of n clauses. Please, make sure to check the samples in order to properly understand how the formula looks like.Natalia is more into fight than theory, so she asked you to tell her the number of answers to this equation. More precisely, you need to find the number of ways to set x1, ..., xm with true and false (out of total of 2m ways) so that the equation is satisfied. Since this number can be extremely large, you need to print the answer modulo 109 + 7.Please, note that some variable may appear twice in one clause, or not appear in the equation at all (but still, setting it to false or true gives different ways to set variables). | 256 megabytes | //package round366;
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 C {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
// int[] f = new int[2];
// for(int i = 0;i < 16;i++){
// int a = i>>>3&1, b = i>>>2&1, c = i>>>1&1, d = i>>>0&1;
//// f[(a|b)^((b^1)|c)^(c|(d^1))^(a^1)]++;
//// f[(a|b)^((b^1)|c)^(a^1)]++;
// f[(a|b)^(a^1)]++;
//// f[(a^1)]++;
// }
int mod = 1000000007;
int n = ni(), m = ni();
int[] from = new int[n];
int[] to = new int[n];
int[] w = new int[n];
int[][] xnf = new int[n][];
int[] ff = new int[n];
int[] tt = new int[n];
int p = 0;
int q = 0;
for(int i = 0;i < n;i++){
int L = ni();
xnf[i] = na(L);
if(L >= 2 && Math.abs(xnf[i][0]) != Math.abs(xnf[i][1])){
from[p] = Math.abs(xnf[i][0]);
to[p] = Math.abs(xnf[i][1]);
w[p] = i;
p++;
}else{
ff[q] = Math.abs(xnf[i][0]);
tt[q] = i;
q++;
}
}
int[][] xg = packD(m+1, ff, tt, q);
int[][][] g = packWU(m+1, from, to, w, p);
long[] gdp = new long[]{1, 0};
boolean[] ved = new boolean[m+1];
for(int i = 1;i <= m;i++){
if(ved[i])continue;
if(g[i].length == 1){
// tr("start", i);
int pre = -1;
long[][] dp = new long[2][2]; // result last
dp[0][0] = 1; dp[0][1] = 1;
for(int cur = i;;){
ved[cur] = true;
dp = one(xg[cur], xnf, dp, mod);
// tr(dp, cur);
if(pre != -1 && g[cur].length == 1)break;
int ind = 0;
int nex = g[cur][0][0]; ind = 0;
if(nex == pre){
nex = g[cur][1][0];
ind = 1;
}
int eid = g[cur][ind][1];
int cocur = -1, conex = -1;
for(int z = 0;z < 2;z++){
if(xnf[eid][z] == -cur)cocur = 1;
if(xnf[eid][z] == cur)cocur = 0;
if(xnf[eid][z] == -nex)conex = 1;
if(xnf[eid][z] == nex)conex = 0;
}
assert cocur != -1;
assert conex != -1;
{
long[][] ndp = new long[2][2];
for(int r = 0;r < 2;r++){
for(int z = 0;z < 2;z++){
for(int y = 0;y < 2;y++){// y->z
int val = (y^cocur) | (z^conex);
ndp[r^val][z] += dp[r][y];
if(ndp[r^val][z] >= mod)ndp[r^val][z] -= mod;
}
}
}
dp = ndp;
}
pre = cur;
cur = nex;
}
// 6 2
// 6 2
// 6 10
// 72+72+360+40
// TTT TF=T
// TTF FF=F
// TFT TT=F
// TFF TT=F
// FFF TT=F
// FFT TT=F
// FTF TF=T
// FTT TT=F
// tr(dp);
long[] gndp = new long[]{0, 0};
for(int z = 0;z < 2;z++){
for(int y = 0;y < 2;y++){
gndp[y^z] += gdp[y] * (dp[z][0]+dp[z][1]);
gndp[y^z] %= mod;
}
}
gdp = gndp;
}else if(g[i].length == 0){
ved[i] = true;
int[] lto = new int[]{0, 0};
for(int u : xg[i]){
int[] x = xnf[u];
for(int z = 0;z < 2;z++){
int res = 0;
for(int v = 0;v < x.length;v++){
if(x[v] > 0){
res |= z;
}else{
res |= z^1;
}
}
lto[z] ^= res;
}
}
long[] gndp = new long[]{0, 0};
for(int z = 0;z < 2;z++){
for(int y = 0;y < 2;y++){
gndp[y^lto[z]] += gdp[y];
gndp[y^lto[z]] %= mod;
}
}
gdp = gndp;
}
}
for(int i = 1;i <= m;i++){
if(ved[i])continue;
// tr("start", i);
long[] trans = new long[2];
for(int first = 0;first < 2;first++){
long[][] dp = new long[2][2]; // result last
dp[0][first] = 1;
int pre = -1;
for(int cur = i;;){
if(pre != -1 && cur == i)break;
dp = one(xg[cur], xnf, dp, mod);
int ind = 0;
int nex = g[cur][0][0]; ind = 0;
if(nex == pre){
nex = g[cur][1][0];
ind = 1;
}
int eid = g[cur][ind][1];
int cocur = -1, conex = -1;
for(int z = 0;z < 2;z++){
if(xnf[eid][z] == -cur)cocur = 1;
if(xnf[eid][z] == cur)cocur = 0;
if(xnf[eid][z] == -nex)conex = 1;
if(xnf[eid][z] == nex)conex = 0;
}
assert cocur != -1;
assert conex != -1;
{
long[][] ndp = new long[2][2];
for(int r = 0;r < 2;r++){
for(int z = 0;z < 2;z++){
for(int y = 0;y < 2;y++){// y->z
int val = (y^cocur) | (z^conex);
ndp[r^val][z] += dp[r][y];
if(ndp[r^val][z] >= mod)ndp[r^val][z] -= mod;
}
}
}
dp = ndp;
}
pre = cur;
cur = nex;
}
trans[0] += dp[0][first];
trans[1] += dp[1][first];
}
long[] gndp = new long[]{0, 0};
for(int z = 0;z < 2;z++){
for(int y = 0;y < 2;y++){
gndp[y^z] += gdp[y] * trans[z];
gndp[y^z] %= mod;
}
}
gdp = gndp;
int pre = -1;
for(int cur = i;;){
if(ved[cur])break;
ved[cur] = true;
int nex = g[cur][0][0];
if(nex == pre){
nex = g[cur][1][0];
}
pre = cur;
cur = nex;
}
}
out.println(gdp[1]);
}
long[][] one(int[] row, int[][] xnf, long[][] dp, int mod)
{
int[] lto = new int[]{0, 0};
for(int u : row){
int[] x = xnf[u];
for(int z = 0;z < 2;z++){
int res = 0;
for(int v = 0;v < x.length;v++){
if(x[v] > 0){
res |= z;
}else{
res |= z^1;
}
}
lto[z] ^= res;
}
}
{
long[][] ndp = new long[2][2];
for(int r = 0;r < 2;r++){
for(int z = 0;z < 2;z++){
ndp[r^lto[z]][z] += dp[r][z];
if(ndp[r^lto[z]][z] >= mod)ndp[r^lto[z]][z] -= mod;
}
}
dp = ndp;
}
return dp;
}
public static int[][] packD(int n, int[] from, int[] to, int sup)
{
int[][] g = new int[n][];
int[] p = new int[n];
for(int i = 0;i < sup;i++)p[from[i]]++;
for(int i = 0;i < n;i++)g[i] = new int[p[i]];
for(int i = 0;i < sup;i++){
g[from[i]][--p[from[i]]] = to[i];
}
return g;
}
public static int[][][] packWU(int n, int[] from, int[] to, int[] w, int sup)
{
int[][][] g = new int[n][][];
int[] p = new int[n];
for(int i = 0;i < sup;i++)p[from[i]]++;
for(int i = 0;i < sup;i++)p[to[i]]++;
for(int i = 0;i < n;i++)g[i] = new int[p[i]][2];
for(int i = 0;i < sup;i++){
--p[from[i]];
g[from[i]][p[from[i]]][0] = to[i];
g[from[i]][p[from[i]]][1] = w[i];
--p[to[i]];
g[to[i]][p[to[i]]][0] = from[i];
g[to[i]][p[to[i]]][1] = w[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 C().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 | ["6 7\n2 4 -2\n2 6 3\n2 -7 1\n2 -5 1\n2 3 6\n2 -2 -5", "8 10\n1 -5\n2 4 -6\n2 -2 -6\n2 -7 9\n2 10 -1\n2 3 -1\n2 -8 9\n2 5 8", "2 3\n2 1 1\n2 -3 3"] | 2 seconds | ["48", "544", "4"] | NoteThe equation in the first sample is:The equation in the second sample is:The equation in the third sample is: | Java 8 | standard input | [
"dp",
"implementation",
"graphs",
"math"
] | e8e5338de3ff4a7c5e60d4507217465e | The first line of input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of clauses and the number of variables respectively. The next n lines contain the formula. The i-th of them starts with an integer ki — the number of literals in the i-th clause. It is followed by ki non-zero integers ai, 1, ..., ai, ki. If ai, j > 0 then vi, j is xai, j otherwise it's negation of x - ai, j (1 ≤ ki ≤ 2, - m ≤ ai, j ≤ m, ai, j ≠ 0). | 2,900 | Print the answer modulo 1 000 000 007 (109 + 7) in one line. | standard output | |
PASSED | 6038ee51d9f4d29e33f8973e289c5878 | train_004.jsonl | 1470578700 | Natalia Romanova is trying to test something on the new gun S.H.I.E.L.D gave her. In order to determine the result of the test, she needs to find the number of answers to a certain equation. The equation is of form:Where represents logical OR and represents logical exclusive OR (XOR), and vi, j are some boolean variables or their negations. Natalia calls the left side of the equation a XNF formula. Each statement in brackets is called a clause, and vi, j are called literals.In the equation Natalia has, the left side is actually a 2-XNF-2 containing variables x1, x2, ..., xm and their negations. An XNF formula is 2-XNF-2 if: For each 1 ≤ i ≤ n, ki ≤ 2, i.e. the size of each clause doesn't exceed two. Each variable occurs in the formula at most two times (with negation and without negation in total). Please note that it's possible that a variable occurs twice but its negation doesn't occur in any clause (or vice versa). Natalia is given a formula of m variables, consisting of n clauses. Please, make sure to check the samples in order to properly understand how the formula looks like.Natalia is more into fight than theory, so she asked you to tell her the number of answers to this equation. More precisely, you need to find the number of ways to set x1, ..., xm with true and false (out of total of 2m ways) so that the equation is satisfied. Since this number can be extremely large, you need to print the answer modulo 109 + 7.Please, note that some variable may appear twice in one clause, or not appear in the equation at all (but still, setting it to false or true gives different ways to set variables). | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
static final int P = 1_000_000_007;
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
static class Edge {
int from, to;
int signFrom, signTo, id;
public Edge(int signFrom, int signTo, int id) {
this.signFrom = signFrom;
this.signTo = signTo;
this.id = id;
from = Math.abs(signFrom);
to = Math.abs(signTo);
}
}
int eval(int x, int y, int signX, int signY) {
return ((x == 0) == (signX < 0)) || ((y == 0) == (signY < 0)) ? 1 : 0;
}
int solve(int m, int n, int[][] a) {
int rhs = 1;
List<Edge>[] g;
g = new List[n + 1];
for (int i = 1; i <= n; i++) {
g[i] = new ArrayList<>(2);
}
boolean[] inLhs = new boolean[n + 1];
for (int i = 0; i < m; i++) {
int k = a[i].length;
int[] tmp = a[i];
if (k == 2 && tmp[0] == tmp[1]) {
k = 1;
tmp = new int[] { tmp[0] };
}
if (k == 2 && tmp[0] == -tmp[1]) {
rhs ^= 1;
continue;
}
// System.err.println(tmp[0] + " " + tmp[1]);
if (k == 2) {
g[Math.abs(tmp[0])].add(new Edge(tmp[0], tmp[1], i));
g[Math.abs(tmp[1])].add(new Edge(tmp[1], tmp[0], i));
} else {
inLhs[Math.abs(tmp[0])] ^= true;
if (tmp[0] < 0) {
rhs ^= 1;
}
}
}
int[] ret = { 1, 0 };
boolean[] vis = new boolean[n + 1];
for (int i = 1; i <= n; i++) {
if (!vis[i] && g[i].size() == 1) {
int[][][] dp = new int[2][2][2]; // first, last, value
dp[0][0][0]++;
dp[1][1][inLhs[i] ? 1 : 0]++;
vis[i] = true;
int v = i;
Edge e = g[v].get(0);
while (true) {
int u = e.to;
vis[u] = true;
int signU = e.signTo;
int signV = e.signFrom;
int[][][] nxt = new int[2][2][2];
for (int first = 0; first < 2; first++)
for (int prev = 0; prev < 2; prev++)
for (int value = 0; value < 2; value++) {
for (int now = 0; now < 2; now++) {
int newValue = value
^ ((inLhs[u] && now == 1) ? 1 : 0)
^ eval(prev, now, signV, signU);
nxt[first][now][newValue] += dp[first][prev][value];
nxt[first][now][newValue] %= P;
}
}
dp = nxt;
if (g[u].size() == 1) {
break;
}
Edge newE = g[u].get(g[u].get(0).id == e.id ? 1 : 0);
v = u;
e = newE;
}
int[] ways = new int[2];
for (int first = 0; first < 2; first++)
for (int last = 0; last < 2; last++)
for (int value = 0; value < 2; value++) {
ways[value] += dp[first][last][value];
ways[value] %= P;
}
int[] newRet = new int[2];
for (int was = 0; was < 2; was++)
for (int now = 0; now < 2; now++) {
newRet[(was + now) % 2] += (int) ((long) ret[was]
* ways[now] % P);
newRet[(was + now) % 2] %= P;
}
ret = newRet;
}
}
// System.err.println(Arrays.toString(ret));
// System.err.println(rhs);
// System.err.println(Arrays.toString(inLhs));
for (int i = 1; i <= n; i++) {
if (!vis[i] && g[i].size() == 2) {
int[][][] dp = new int[2][2][2]; // first, last, value
dp[0][0][0]++;
dp[1][1][inLhs[i] ? 1 : 0]++;
vis[i] = true;
int v = i;
Edge e = g[v].get(0);
while (true) {
int u = e.to;
if (u == i) {
break;
}
vis[u] = true;
int signU = e.signTo;
int signV = e.signFrom;
int[][][] nxt = new int[2][2][2];
for (int first = 0; first < 2; first++)
for (int prev = 0; prev < 2; prev++)
for (int value = 0; value < 2; value++) {
for (int now = 0; now < 2; now++) {
int newValue = value
^ (inLhs[u] && now == 1 ? 1 : 0)
^ eval(prev, now, signV, signU);
nxt[first][now][newValue] += dp[first][prev][value];
nxt[first][now][newValue] %= P;
}
}
dp = nxt;
if (g[u].size() == 1) {
throw new AssertionError();
}
Edge newE = g[u].get(g[u].get(0).id == e.id ? 1 : 0);
v = u;
e = newE;
}
int[][][] nxt = new int[2][2][2];
for (int first = 0; first < 2; first++)
for (int last = 0; last < 2; last++)
for (int value = 0; value < 2; value++) {
int newValue = value
^ eval(last, first, e.signFrom, e.signTo);
nxt[first][last][newValue] += dp[first][last][value];
nxt[first][last][newValue] %= P;
}
dp = nxt;
int[] ways = new int[2];
for (int first = 0; first < 2; first++)
for (int last = 0; last < 2; last++)
for (int value = 0; value < 2; value++) {
ways[value] += dp[first][last][value];
ways[value] %= P;
}
int[] newRet = new int[2];
for (int was = 0; was < 2; was++)
for (int now = 0; now < 2; now++) {
newRet[(was + now) % 2] += (int) ((long) ret[was]
* ways[now] % P);
newRet[(was + now) % 2] %= P;
}
ret = newRet;
}
}
for (int i = 1; i <= n; i++) {
if (g[i].isEmpty()) {
int[] newRet = new int[2];
for (int was = 0; was < 2; was++)
for (int now = 0; now < 2; now++) {
int newIdx = (was + ((now == 1 && inLhs[i]) ? 1 : 0)) % 2;
newRet[newIdx] += ret[was];
newRet[newIdx] %= P;
}
ret = newRet;
}
}
return ret[rhs];
}
int brute(int m, int n, int[][] a) {
int ret = 0;
for (int mask = 0; mask < 1 << n; mask++) {
int cur = 0;
outer: for (int i = 0; i < m; i++) {
for (int j = 0; j < a[i].length; j++) {
int have = get(mask, Math.abs(a[i][j]) - 1);
int need = a[i][j] < 0 ? 0 : 1;
if (have == need) {
cur ^= 1;
continue outer;
}
}
}
if (cur == 1) {
ret++;
}
}
return ret;
}
int get(int mask, int i) {
return (mask >> i) & 1;
}
Random rng = new Random();
void oneTest(int n) throws IOException {
int m = rng.nextInt(n);
int[] cnt = new int[n];
int[][] a = new int[m][];
for (int i = 0; i < m; i++) {
int k = rng.nextInt(2) + 1;
a[i] = new int[k];
for (int j = 0; j < k; j++) {
int idx;
do {
idx = rng.nextInt(n);
} while (cnt[idx] == 2);
cnt[idx]++;
a[i][j] = (idx + 1) * (rng.nextBoolean() ? -1 : 1);
}
}
System.err.println(m + " " + n + " " + Arrays.deepToString(a));
int wrong = solve(m, n, a);
int slow = brute(m, n, a);
if (wrong != slow) {
throw new AssertionError(m + " " + n + " " + Arrays.deepToString(a));
}
}
C() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int m = nextInt();
int n = nextInt();
int[][] a = new int[m][];
for (int i = 0; i < m; i++) {
int k = nextInt();
a[i] = new int[k];
for (int j = 0; j < k; j++) {
a[i][j] = nextInt();
}
}
out.println(solve(m, n, a));
// out.println(brute(m, n, a));
out.close();
// while (true) {
// oneTest(4);
// }
}
public static void main(String[] args) throws IOException {
new C();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["6 7\n2 4 -2\n2 6 3\n2 -7 1\n2 -5 1\n2 3 6\n2 -2 -5", "8 10\n1 -5\n2 4 -6\n2 -2 -6\n2 -7 9\n2 10 -1\n2 3 -1\n2 -8 9\n2 5 8", "2 3\n2 1 1\n2 -3 3"] | 2 seconds | ["48", "544", "4"] | NoteThe equation in the first sample is:The equation in the second sample is:The equation in the third sample is: | Java 8 | standard input | [
"dp",
"implementation",
"graphs",
"math"
] | e8e5338de3ff4a7c5e60d4507217465e | The first line of input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of clauses and the number of variables respectively. The next n lines contain the formula. The i-th of them starts with an integer ki — the number of literals in the i-th clause. It is followed by ki non-zero integers ai, 1, ..., ai, ki. If ai, j > 0 then vi, j is xai, j otherwise it's negation of x - ai, j (1 ≤ ki ≤ 2, - m ≤ ai, j ≤ m, ai, j ≠ 0). | 2,900 | Print the answer modulo 1 000 000 007 (109 + 7) in one line. | standard output | |
PASSED | 5bec80d98518a29f05216eb4c4f0cbd7 | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.util.*;
public class Main {
private static final long MOD = 1000000007;
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int x = scan.nextInt();
// be care of Overflow!!!
long[] arr = new long[n];
read(scan, arr);
long sum = 0;
for (long val : arr) {
sum += val;
}
for (int i = 0; i < n; i++) {
arr[i] = sum - arr[i];
}
long r = arr[n - 1];
int count = 1;
int index = n - 2;
while (true) {
while (index >= 0 && arr[index] == r) {
index--;
count++;
}
if (index < 0) {
break;
}
while (arr[index] > r && count % x == 0) {
count /= x;
r++;
}
if (arr[index] > r) {
break;
}
}
while (count % x == 0) {
count /= x;
r++;
}
if (r > sum) {
r = sum;
}
System.out.println(pow(x, r));
scan.close();
}
private static long pow(long base, long r) {
if (r == 0) {
return 1;
}
long half = pow(base, r / 2);
long res = (half * half) % MOD;
if (r % 2 != 0) {
res = (res * base) % MOD;
}
return res;
}
private static void print(int[] arr) {
System.out.print(arr[0]);
for (int i = 1; i < arr.length; i++) {
System.out.print(" ");
System.out.print(arr[i]);
}
System.out.println();
}
private static void print(long[] arr) {
System.out.print(arr[0]);
for (int i = 1; i < arr.length; i++) {
System.out.print(" ");
System.out.print(arr[i]);
}
System.out.println();
}
private static void read(Scanner scan, int[]... arrs) {
int len = arrs[0].length;
for (int i = 0; i < len; i++) {
for (int[] arr : arrs) {
arr[i] = scan.nextInt();
}
}
}
private static void read(Scanner scan, long[]... arrs) {
int len = arrs[0].length;
for (int i = 0; i < len; i++) {
for (long[] arr : arrs) {
arr[i] = scan.nextLong();
}
}
}
private static void decreaseByOne(int[]... arrs) {
for (int[] arr : arrs) {
for (int i = 0; i < arr.length; i++) {
arr[i] --;
}
}
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 0fc25bd0c56a86049a51bae6d340bddf | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class C_209 {
static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st = new StringTokenizer("");
public static void main(String[] args) throws Exception {
int n = readInt();
int x = readInt();
int m = 1000000007;
ArrayList<Integer> a = new ArrayList();
long sum = 0;
for(int i = 0; i < n; ++i) {
a.add(readInt());
sum += a.get(i);
}
LinkedList<Long> exp = new LinkedList();
for(int i = 0; i < n; ++i)
exp.add(sum - a.get(i));
Collections.sort(exp);
while(!exp.isEmpty()) {
int count = 1;
long e = exp.pop();
while(!exp.isEmpty() && e == exp.peek()) {
++count;
exp.pop();
}
if(count%x == 0) {
for(int i = 0; i < count/x; ++i)
exp.push(e+1);
} else {
System.out.println(BigInteger.valueOf(x).modPow(BigInteger.valueOf(Math.min(e, sum)), BigInteger.valueOf(m)));
exp.clear();
}
}
}
static String readString() throws Exception {
while(!st.hasMoreTokens())
st = new StringTokenizer(stdin.readLine());
return st.nextToken();
}
static int readInt() throws Exception {
return Integer.parseInt(readString());
}
} | Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | b3aef61a451b9a389985e66e1ed40fa8 | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long x = in.nextLong();
BigInteger xB = BigInteger.valueOf(x);
BigInteger p = BigInteger.valueOf(1000000007);
long sum = 0;
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextLong();
if (i + 1 < n) {
sum += a[i];
}
}
long curpow = 0;
long curN = 0;
boolean ok = true;
for (int i = n-1; i >= 0; i--) {
while (a[n-1] - a[i] != curpow) {
if (curN % x == 0) {
curpow++;
curN /= x;
if (curpow > a[n-1]) {
ok = false;
break;
}
} else {
ok = false;
break;
}
}
if (!ok) {
break;
}
curN++;
}
while (curN > 0 && curN % x == 0) {
curpow++;
curN /= x;
}
sum += Math.min(a[n-1], curpow);
BigInteger pgcd = xB.modPow(BigInteger.valueOf(sum), p);
/* if (eqN % x == 0) {
BigInteger num = BigInteger.valueOf(0);
BigInteger deno = xB.pow(a[n-1]);
for (int i = 0; i < n; i++) {
num = num.add(xB.modPow(BigInteger.valueOf(a[n-1]-a[i]),deno));
}
//System.out.println(num);
//pgcd = pgcd.multiply(num).mod(p);
pgcd = pgcd.multiply(num.gcd(deno).mod(p)).mod(p);
}*/
System.out.println(pgcd);
in.close();
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 5370ad21eea6820c7da821556f013673 | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static BufferedReader reader
= new BufferedReader(new InputStreamReader(System.in));
static StringBuilder out = new StringBuilder();
public static void main(String[] args){
long[] inp = nextLongArray();
long n, x;
n = inp[0]; x = inp[1];
long[] a = nextLongArray();
BigInteger s = BigInteger.valueOf(0);
for (long i : a) s = s.add(BigInteger.valueOf(i));
TreeMap<BigInteger, Long> coefficient = new TreeMap<BigInteger, Long>();
// coefficient.get(i) is the coefficiet of x ^ i
for (long i : a){
BigInteger key = s.subtract(BigInteger.valueOf(i));
if (coefficient.containsKey(key)){
coefficient.put(key, coefficient.get(key) + 1);
} else {
coefficient.put(key, (long) 1);
}
}
BigInteger key = coefficient.firstKey();
while (true){
long c = coefficient.get(key);
if (c < x){
break;
} else {
int cnt = 0;
while (c % x == 0){
c /= x;
cnt ++;
}
if (cnt == 0){
break;
}
BigInteger newKey = key.add(BigInteger.valueOf(cnt));
if (coefficient.containsKey(newKey)){
coefficient.put(newKey, coefficient.get(newKey) + c);
} else {
coefficient.put(newKey, Long.valueOf(c % x));
}
key = coefficient.ceilingKey(key.add(BigInteger.valueOf(1)));
// System.out.println(key);
}
}
// System.out.println(x + " " + key);
if (key.compareTo(s) == 1){
key = s;
}
long ans = BigInteger.valueOf(x).modPow(key, BigInteger.valueOf((long) 1e9 + 7)).longValue();
out.append(ans);
System.out.println(out);
}
static long myLog(long a, long b){
if (b == 1){
return -1;
}
long cnt = 0;
long acc = 1;
while (acc < b){
acc *= a;
cnt ++;
}
return cnt == b ? cnt : -1;
}
static boolean isInteger(double d){
return Math.abs(d - Math.floor(0.5 + d)) < 0.000001;
}
// the followings are methods to take care of inputs.
static int nextInt(){
return Integer.parseInt(nextLine());
}
static long nextLong(){
return Long.parseLong(nextLine());
}
static int[] nextIntArray(){
String[] inp = nextLine().split("\\s+");
int[] ary = new int[inp.length]; for (int i = 0; i < ary.length; i++){
ary[i] = Integer.parseInt(inp[i]);
}
return ary;
}
static int[] nextIntArrayFrom1(){
String[] inp = nextLine().split("\\s+");
int[] ary = new int[inp.length + 1];
for (int i = 0; i < inp.length; i++){
ary[i+1] = Integer.parseInt(inp[i]);
}
return ary;
}
static long[] nextLongArray(){
String[] inp = nextLine().split("\\s+");
long[] ary = new long[inp.length];
for (int i = 0; i < inp.length; i++){
ary[i] = Long.parseLong(inp[i]);
}
return ary;
}
static long[] nextLongArrayFrom1(){
String[] inp = nextLine().split("\\s+");
long[] ary = new long[inp.length + 1];
for (int i = 0; i < inp.length; i++){
ary[i+1] = Long.parseLong(inp[i]);
}
return ary;
}
static String nextLine(){
try {
return reader.readLine().trim();
} catch (Exception e){}
return null;
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 57cfe36286fa83c7d6be4eb06ded573d | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static BufferedReader reader
= new BufferedReader(new InputStreamReader(System.in));
static StringBuilder out = new StringBuilder();
public static void main(String[] args){
long[] inp = nextLongArray();
long n, x;
n = inp[0]; x = inp[1];
long[] a = nextLongArray();
long s = 0;
for (long i : a) s += i;
TreeMap<Long, Long> coefficient = new TreeMap<Long, Long>();
// coefficient.get(i) is the coefficiet of x ^ i
for (long i : a){
long key = s - i;
if (coefficient.containsKey(key)){
coefficient.put(key, coefficient.get(key) + 1);
} else {
coefficient.put(key, (long) 1);
}
}
long key = coefficient.firstKey();
while (true){
long c = coefficient.get(key);
// c * x ^ key -> c * x ^ (key + pow)
int pow = 0;
while (c % x == 0){
c /= x;
pow ++;
}
if (pow == 0){
break;
}
long newKey = key + pow;
if (coefficient.containsKey(newKey)){
coefficient.put(newKey, coefficient.get(newKey) + c);
} else {
coefficient.put(newKey, Long.valueOf(c));
}
key = coefficient.ceilingKey(key + 1);
}
if (key > s){
key = s;
}
BigInteger Key = BigInteger.valueOf(key);
BigInteger Mod = BigInteger.valueOf((long) 1e9 + 7);
BigInteger X = BigInteger.valueOf(x);
long ans = X.modPow(Key , Mod).longValue();
out.append(ans);
System.out.println(out);
}
static long myLog(long a, long b){
if (b == 1){
return -1;
}
long cnt = 0;
long acc = 1;
while (acc < b){
acc *= a;
cnt ++;
}
return cnt == b ? cnt : -1;
}
static boolean isInteger(double d){
return Math.abs(d - Math.floor(0.5 + d)) < 0.000001;
}
// the followings are methods to take care of inputs.
static int nextInt(){
return Integer.parseInt(nextLine());
}
static long nextLong(){
return Long.parseLong(nextLine());
}
static int[] nextIntArray(){
String[] inp = nextLine().split("\\s+");
int[] ary = new int[inp.length]; for (int i = 0; i < ary.length; i++){
ary[i] = Integer.parseInt(inp[i]);
}
return ary;
}
static int[] nextIntArrayFrom1(){
String[] inp = nextLine().split("\\s+");
int[] ary = new int[inp.length + 1];
for (int i = 0; i < inp.length; i++){
ary[i+1] = Integer.parseInt(inp[i]);
}
return ary;
}
static long[] nextLongArray(){
String[] inp = nextLine().split("\\s+");
long[] ary = new long[inp.length];
for (int i = 0; i < inp.length; i++){
ary[i] = Long.parseLong(inp[i]);
}
return ary;
}
static long[] nextLongArrayFrom1(){
String[] inp = nextLine().split("\\s+");
long[] ary = new long[inp.length + 1];
for (int i = 0; i < inp.length; i++){
ary[i+1] = Long.parseLong(inp[i]);
}
return ary;
}
static String nextLine(){
try {
return reader.readLine().trim();
} catch (Exception e){}
return null;
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | c8802e410d845c5f808dffc16e6b9122 | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static BufferedReader reader
= new BufferedReader(new InputStreamReader(System.in));
static StringBuilder out = new StringBuilder();
public static void main(String[] args){
long[] inp = nextLongArray();
long n, x;
n = inp[0]; x = inp[1];
long[] a = nextLongArray();
long s = 0;
for (long i : a) s += i;
TreeMap<Long, Long> coefficient = new TreeMap<Long, Long>();
// coefficient.get(i) is the coefficiet of x ^ i
for (long i : a){
long key = s - i;
if (coefficient.containsKey(key)){
coefficient.put(key, coefficient.get(key) + 1);
} else {
coefficient.put(key, (long) 1);
}
}
long key = coefficient.firstKey();
while (true){
long c = coefficient.get(key);
// c * x ^ key -> c * x ^ (key + pow)
int pow = 0;
while (c % x == 0){
c /= x;
pow ++;
}
if (pow == 0){
break;
}
long newKey = key + pow;
if (coefficient.containsKey(newKey)){
coefficient.put(newKey, coefficient.get(newKey) + c);
} else {
coefficient.put(newKey, Long.valueOf(c));
}
key = coefficient.ceilingKey(key + 1);
}
if (key > s){
key = s;
}
BigInteger Key = BigInteger.valueOf(key);
BigInteger Mod = BigInteger.valueOf((long) 1e9 + 7);
BigInteger X = BigInteger.valueOf(x);
long ans = X.modPow(Key , Mod).longValue();
out.append(ans);
System.out.println(out);
}
// the followings are methods to take care of inputs.
static int nextInt(){
return Integer.parseInt(nextLine());
}
static long nextLong(){
return Long.parseLong(nextLine());
}
static int[] nextIntArray(){
String[] inp = nextLine().split("\\s+");
int[] ary = new int[inp.length]; for (int i = 0; i < ary.length; i++){
ary[i] = Integer.parseInt(inp[i]);
}
return ary;
}
static int[] nextIntArrayFrom1(){
String[] inp = nextLine().split("\\s+");
int[] ary = new int[inp.length + 1];
for (int i = 0; i < inp.length; i++){
ary[i+1] = Integer.parseInt(inp[i]);
}
return ary;
}
static long[] nextLongArray(){
String[] inp = nextLine().split("\\s+");
long[] ary = new long[inp.length];
for (int i = 0; i < inp.length; i++){
ary[i] = Long.parseLong(inp[i]);
}
return ary;
}
static long[] nextLongArrayFrom1(){
String[] inp = nextLine().split("\\s+");
long[] ary = new long[inp.length + 1];
for (int i = 0; i < inp.length; i++){
ary[i+1] = Long.parseLong(inp[i]);
}
return ary;
}
static String nextLine(){
try {
return reader.readLine().trim();
} catch (Exception e){}
return null;
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | b6d7bd1edfeb91dfce7805897436b08e | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class cf359c {
static FastIO in = new FastIO(), out = in;
static long mod = (long)1e9 + 7;
public static void main(String[] args) {
long n = in.nextLong();
long x = in.nextLong();
long[] v = new long[(int)n];
long sum = 0;
for(int i=0; i<n; i++)
sum += v[i]=in.nextLong();
Cluster cluster = new Cluster();
for(long z : v) cluster.add(sum-z, 1);
long ret = 0;
while(true) {
long a = cluster.min();
long b = cluster.get(a);
if(b%x == 0) {
cluster.remove(a, b);
cluster.add(a+1, b/x);
}
else {
ret = a;
break;
}
}
if(ret > sum) ret = sum;
out.println(pow(x,ret));
out.close();
}
static long pow(long x, long p) {
if(p == 0) return 1;
long v = pow(x,p>>1);
v = (v*v)%mod;
if((p&1)==1) v=(v*x)%mod;
return v;
}
static class Cluster {
TreeMap<Long, Long> map = new TreeMap<Long,Long>();
long min() {
return map.firstKey();
}
void add(long x, long v) {
set(x, get(x)+v);
}
void remove(long x, long v) {
set(x, get(x)-v);
}
void set(long x, long v) {
if(v == 0) map.remove(x);
else map.put(x, v);
}
long get(long x) {
if(map.containsKey(x)) return map.get(x);
return 0;
}
public String toString() {
return map.toString();
}
}
static class FastIO extends PrintWriter {
BufferedReader br;
StringTokenizer st;
public FastIO() {
this(System.in, System.out);
}
public FastIO(InputStream in, OutputStream out) {
super(new BufferedWriter(new OutputStreamWriter(out)));
br = new BufferedReader(new InputStreamReader(in));
scanLine();
}
public void scanLine() {
try {
st = new StringTokenizer(br.readLine().trim());
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public int numTokens() {
if (!st.hasMoreTokens()) {
scanLine();
return numTokens();
}
return st.countTokens();
}
public String next() {
if (!st.hasMoreTokens()) {
scanLine();
return next();
}
return st.nextToken();
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | e8849b86871697be1b1c9ee61b1599e8 | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.Collections.*;
import static java.util.Collections.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.math.BigInteger.*;
import static java.lang.Character.*;
public class Main {
void run(){
// boolean oj = true;
// boolean oj = false;
Locale.setDefault(Locale.US);
boolean oj = System.getProperty("ONLINE_JUDGE")!=null;
String fileName = oj? "castle" : "dwarf";
try {
if( oj ){
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
}
else{
br = new BufferedReader(new FileReader(fileName+".in" ));
out = new PrintWriter (new FileWriter(fileName+".out"));
}
} catch (Exception e) {
MLE();
}
long tb = System.currentTimeMillis();
solve();
// if( !oj )
// out.println("TIME: " + (System.currentTimeMillis() - tb) / 1e3) ;
exit(0);
}
BufferedReader br;
StringTokenizer st;
PrintWriter out;
String next(){
while( st==null || !st.hasMoreElements() ){
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
return null;
}
}
return st.nextToken();
}
String nextLine(){
try {
return br.readLine();
} catch (Exception e) {
return null;
}
}
int nextInt(){ return Integer.parseInt(next()); }
double nextDouble(){ return Double.parseDouble(next()); }
long nextLong(){ return Long.parseLong(next()); }
void exit( int val ){
out.flush();
System.exit(val);
}
void MLE(){
int[][] arr = new int[1024*1024][];
for( int i = 0; i < 1024*1024; ++i )
arr[i] = new int[1024*1024];
}
public static void main(String[] args) {
new Main().run();
}
int n;
long x;
long [] a;
long ansPow, sumA;
TreeMap<Long,Long> tm;
void add( long pw, long coef ){
if( !tm.containsKey(pw) )
tm.put( pw, coef );
else
tm.put( pw, tm.get(pw) + coef );
}
void solve(){
ansPow = 0;
n = nextInt();
x = nextInt();
a = new long[n];
sumA = 0;
for( int i = 0; i < n; ++i ){
sumA += a[i] = nextInt();
}
sort(a);
ansPow = sumA - a[n-1];
tm = new TreeMap<>();
for( long ai : a )
add( sumA - ansPow - ai, 1 );
while(true){
long pw = tm.firstKey();
long coef = tm.pollFirstEntry().getValue();
if( coef % x == 0 ){
while( coef % x == 0 ){
coef /= x;
++pw;
}
add( pw, coef );
}
else{
add( pw, coef );
break;
}
}
//
ansPow += tm.firstKey();
ansPow = min( ansPow, sumA );
out.println( valueOf(x)
.modPow(valueOf(ansPow),valueOf((int)1e9+7)) );
}
} | Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 412425ccedb90e3aca03815077ac2eaa | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.InputMismatchException;
import java.util.TreeMap;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Nipuna Samarasekara
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
/////////////////////////////////////////////////////////////
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n=in.nextInt(),p=in.nextInt();
int[] A=in.readIntArray(n);
long sum=0;
TreeMap<Integer,Integer> tm=new TreeMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
sum+=A[i];
if(tm.containsKey(A[i]))tm.put(A[i],tm.get(A[i])+1);
else tm.put(A[i],1);
}
int ans=tm.lastKey();
int chk=0;
while(chk==0){
chk=1;
int k=tm.lastKey();
ans=k;
if(tm.get(k)%p==0){
chk=0;
int hh=tm.get(k);
tm.remove(k);
while(hh%p==0){
hh/=p;k--;
}
if(tm.containsKey(k))tm.put(k,tm.get(k)+hh);
else tm.put(k,hh);
}
}
ans=Math.max(0,ans);
sum-=ans;
long ret= modPow(p,sum);
out.println(ret);
}
static long MOD=1000000007;
static long modPow(long a, long pow) {
long res = 1;
while (pow > 0) {
if ((pow & 1) != 0) {
res = res * a % MOD;
}
pow >>= 1;
a = a * a % MOD;
}
return res;
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
public int[] readIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 0227e4e68e553ce3013057382d742f9c | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.InputMismatchException;
import java.util.TreeMap;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Nipuna Samarasekara
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
/////////////////////////////////////////////////////////////
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n=in.nextInt(),p=in.nextInt();
int[] A=in.readIntArray(n);
long sum=0;
TreeMap<Integer,Integer> tm=new TreeMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
sum+=A[i];
if(tm.containsKey(A[i]))tm.put(A[i],tm.get(A[i])+1);
else tm.put(A[i],1);
}
int ans=tm.lastKey();
int chk=0;
while(chk==0){
chk=1;
int k=tm.lastKey();
ans=k;
if(tm.get(k)%p==0){
chk=0;
int hh=tm.get(k);
tm.remove(k);
while(hh%p==0){
hh/=p;k--;
}
if(tm.containsKey(k))tm.put(k,tm.get(k)+hh);
else tm.put(k,hh);
}
}
ans=Math.max(0,ans) ;
sum-=ans;
long ret= modPow(p,sum);
out.println(ret);
}
static long MOD=1000000007;
static long modPow(long a, long pow) {
long res = 1;
while (pow > 0) {
if ((pow & 1) != 0) {
res = res * a % MOD;
}
pow >>= 1;
a = a * a % MOD;
}
return res;
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
public int[] readIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 65e3f61e570939ad02eb110fb6a8fdaa | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;
import static java.lang.Comparable.*;
import java.util.*;
import java.io.*;
import com.sun.org.apache.bcel.internal.generic.NEW;
public class Main {
public static void main(String[] args) throws IOException {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
final int maxn = 100 * 1000 + 100;
final long mod = 1000 * 1000 * 1000 + 7;
int n;
long x;
long a[] = new long[maxn];
// Pair pairs[] = new Pair[maxn];
// int countP;
// TreeSet<Pair> pairs = new TreeSet<Main.Pair>();
TreeMap<Long, Long> powToC = new TreeMap<Long, Long>();
long binPow(long a, long n) {
if (n == 0)
return 1;
if (n % 2 == 1)
return (a * binPow(a, n - 1)) % mod;
else {
long temp = binPow(a, n / 2);
return (temp * temp) % mod;
}
}
private void run() throws IOException {
// in = new BufferedReader(new FileReader("input.txt"));
// out = new PrintWriter("output.txt");
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
n = nextInt();
x = nextLong();
long degree = 0;
for (int i = 0; i < n; i++)
degree += (a[i] = nextInt());
for (int i = 0; i < n; i++) {
long pow = degree - a[i];
if (powToC.containsKey(pow))
powToC.put(pow, powToC.get(pow) + 1);
else
powToC.put(pow, (long) 1);
}
long ans = 0;
while (powToC.get(powToC.firstKey()) % x == 0) {
long pow = powToC.firstKey();
long k = powToC.remove(pow);
while (k % x == 0) {
pow++;
k /= x;
}
if (powToC.containsKey(pow))
powToC.put(pow, powToC.get(pow) + k);
else
powToC.put(pow, k);
}
long pow = min(degree, powToC.firstKey());
ans = binPow(x, pow);
out.println(ans);
in.close();
out.close();
}
class Pair implements Comparable<Pair> {
long k;
long a;
Pair(long k, long a) {
this.k = k;
this.a = a;
}
public int compareTo(Pair pair) {
if (a != pair.a)
return Long.valueOf(k).compareTo(pair.k);
return Long.valueOf(a).compareTo(pair.a);
}
}
void chk(boolean b) {
if (b)
return;
System.out.println(new Error().getStackTrace()[1]);
exit(999);
}
void deb(String fmt, Object... args) {
System.out.printf(Locale.US, fmt + "%n", args);
}
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 393b3f9724e3c0899f77a8cdcd01bf9e | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes |
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Stack;
import java.util.Vector;
public class Main {
final static long MOD = 1000000007;
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
long x=in.nextLong();
long a[]=new long[n];
long sum=0;
for (int i=0;i<n;i++){
a[i]=in.nextLong();
sum+=a[i];
}
PriorityQueue<Long> hh=new PriorityQueue<Long>();
for (int i=0;i<n;i++){
hh.add(sum-a[i]);
}
long max=0,ge=0;
while(!hh.isEmpty()){
long s=hh.poll();
max=max>s?max:s;
ge=1;
boolean tell=true;
while (ge!=x){
if (!hh.isEmpty()){
long g=hh.poll();
if (g!=s) {tell=false;break;}
ge++;
}else{
tell=false;break;
}
}
if (tell) hh.add(s+1); else break;
}
if (max>sum) max=sum;
System.out.println(power(x, max, 1000000007));
}
static int power(long x,long n,long k)
{ // x^n % k
long res=1;
while (n>0){
if (n%2==0){
x=(x*x)%k;
n/=2;
}else{
n--;
res=(res*x)%k;
}
}
return (int)(res%k);
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | ea3634f92a7fdc4feeae2036de41172d | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 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.math.BigInteger;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;
public class C {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
static class Que implements Comparable<Que> {
long pow, koef;
public int compareTo(Que arg0) {
if (this.pow>arg0.pow)
return 1;
if (this.pow<arg0.pow)
return -1;
return 0;
}
public Que(long pow, long koef) {
this.pow = pow;
this.koef = koef;
}
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = nextInt();
int x = nextInt();
int[]a = new int[n+1];
long sum = 0;
for (int i = 1; i <= n; i++) {
a[i] = nextInt();
sum += a[i];
}
Long[]pow = new Long[n+1];
for (int i = 1; i <= n; i++) {
pow[i] = sum-a[i];
}
Arrays.sort(pow, 1, n+1);
long[] p = new long[n+1];
for (int i = 1; i <= n; i++) {
p[i] = pow[i].longValue();
}
long gcdpow = 0;
PriorityQueue<Que> q = new PriorityQueue<Que>();
for (int i = 1; i <= n; i++) {
q.add(new Que(p[i], 1));
}
while (!q.isEmpty()) {
long pp = q.peek().pow;
long ss = q.poll().koef;
while (!q.isEmpty() && q.peek().pow==pp) {
ss += q.poll().koef;
}
gcdpow = pp;
if (gcdpow > sum)
break;
if (ss % x != 0)
break;
q.add(new Que(pp+1, ss/x));
}
gcdpow = Math.min(gcdpow, sum);
long ans = BigInteger.valueOf(x).modPow(BigInteger.valueOf(gcdpow), BigInteger.valueOf((long)(1e9+7))).longValue();
System.out.println(ans);
pw.close();
}
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 | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | ffe8ee4792bbf890e81e080c5cf05d1c | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.*;
public class Main {
static StreamTokenizer in = new StreamTokenizer(System.in);
static int ni () throws Exception{
in.nextToken();
return (int)in.nval;
}
public static void main(String[] args) throws Exception {
int n1 = ni();
long p1 = ni();
long[] l1 = new long[n1];
long total = 0;
for (int i = 0; i < n1; i++){
l1[i] = ni();
total += l1[i];
}
TreeMap<Long, Long> m1 = new TreeMap<>();
for (int i = 0; i < n1; i++){
add(total - l1[i], m1);
}
long ptr = total - l1[l1.length - 1];
for (;;){
long v1 = m1.get(ptr);
if (v1 % p1 == 0){
m1.remove(ptr);
}
if (v1 >= p1) add(ptr + 1l, m1, v1 / p1);
Long next = m1.higherKey(ptr);
if (next == null) break;
ptr = next;
}
// px(m1);
long minPow = m1.firstKey();
out.println(pow(p1, Math.min(minPow, total)));
out.flush();
}
static void px(Object ...objects){
System.out.println(Arrays.deepToString(objects));
}
static PrintWriter out = new PrintWriter(System.out);
static long MOD = 1_000_000_007;
static long pow(long base, long pow){
if (pow == 0) return 1l;
if (pow == 1) return base % MOD;
long half = pow(base, pow >> 1);
half = half * half % MOD;
if (pow % 2l == 1l){
half *= base;
half %= MOD;
}
return half;
}
static void add(long n1, TreeMap<Long, Long> m1){
long old = m1.containsKey(n1) ? m1.get(n1) : 0;
m1.put(n1, old + 1l);
}
static void add(long n1, TreeMap<Long, Long> m1, long val){
long old = m1.containsKey(n1) ? m1.get(n1) : 0;
if (old + val != 0) m1.put(n1, old + val);
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 21f2366426422f883f4084a127b4a731 | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {
}
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
private void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
final long MOD = 1000 * 1000 * 1000 + 7;
class Pair implements Comparable<Pair>{
long first,second;
public Pair(long f, long s){
first = f;
second = s;
}
public int compareTo(Pair o) {
return Long.valueOf(first).compareTo(o.first);
}
}
long binpow(long a, long n){
if(n == 0)
return 1L;
long b = binpow(a,n/2) % MOD;
b = (b*b) % MOD;
if(n % 2 == 1)
b = (b*a)%MOD;
return b;
}
public void solve() throws IOException{
int n = nextInt();
long x = nextLong();
int[] a = new int[n];
long t = 0;
for(int i = 0; i < n; i++){
a[i] = nextInt();
t += (long)a[i];
}
TreeSet<Pair> set = new TreeSet<Pair>();
TreeMap<Long, Long> map = new TreeMap<Long, Long>();
for(int i = 0; i < n; i++){
long shift = t - (long)a[i];
Pair p = new Pair(shift,1L);
if(!set.contains(p)){
set.add(p);
} else {
Pair q = set.ceiling(p);
q.second++;
}
// if(map.containsKey(shift))
// map.put(shift,map.get(shift)+1L);
// else
// map.put(shift,1L);
}
while(set.first().second % x == 0){
// while(map.get(map.firstKey()) % x == 0){
// long shift = map.firstKey();
// long deg = map.remove(shift);
// map.put(shift+1,deg/x);
Pair p = set.first();
Pair q = new Pair(p.first + 1,p.second/x);
set.remove(p);
if(!set.contains(q))
set.add(q);
else
set.first().second += q.second;
}
long answer = binpow(x,min(t,set.first().first));
out.println(answer);
}
void chk(boolean b) {
if (b)
return;
System.out.println(new Error().getStackTrace()[1]);
exit(999);
}
void deb(String fmt, Object... args) {
System.out.printf(Locale.US, fmt + "%n", args);
}
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | cbde1da233bbd94a7ff788f2d76d8edb | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.math.*;
import static java.lang.Math.*;
import java.util.*;
public class Main {
static long oo = 2000000000000000000L;
public static void main(String[] args)throws IOException {
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(buf.readLine());
int n = Integer.parseInt(st.nextToken());
int p = Integer.parseInt(st.nextToken());
st = new StringTokenizer(buf.readLine());
long sum = 0;
long []a = new long[n + 1];
for(int i = 0; i < n; i++){
a[i] = Long.parseLong(st.nextToken());
sum += a[i];
}
for(int i = 0; i < n; i++) a[i] = sum - a[i];
a[n] = oo;
Arrays.sort(a);
long pot = a[0];
long res = 1;
long act = a[0];
for(int i = 1; i <= n; i++){
if( act == a[i] )res++;
else{
act = a[i];
long cant = 0;
long tmp = res;
while( tmp % p == 0 ){
cant ++; tmp /= p;
}
if(cant == 0)break;
if(cant < act - pot){
pot += cant; break;
}else{
res /= (long)(pow(p, act - pot));
pot += (act - pot);
res ++;
}
}
}
pot = min(pot,sum);
BigInteger aa = BigInteger.valueOf(p).modPow(BigInteger.valueOf(pot), BigInteger.valueOf(1000000007));
System.out.println(aa);
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | ddc389809ccc66efd6f1102327b0d176 | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.util.Scanner;
import java.util.Arrays;
import java.util.Vector;
public class B {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
long sum = 0;
long n = in.nextInt();
long x = in.nextInt();
long[] a = new long [(int)n];
long[] s = new long [(int)n];
for(int i = 0; i < n; i++) { a[i] = in.nextInt(); sum += a[i]; }
for(int i = 0; i < n; i++) { s[i] = sum - a[i]; }
Arrays.sort(s);
//System.out.println("here");
long l = 0, r = n-1;
long ans = s[0];
while(true) {
//System.out.println("here");
long mark = s[(int)l];
long cnt = 0;
while(cnt+l <= r && s[(int)(cnt+l)] == s[(int)l]) cnt++;
l += cnt;
//System.out.println("here2");
if(cnt % x == 0) {
for(long i = 0; i < cnt/x; i++) s[(int)--l] = mark+1;
ans++;
}
else break;
}
ans = Math.min(ans, sum);
System.out.println(mPow(x, ans));
in.close();
}
public static long mPow(long b, long p) {
long ret = 1;
long mod = 1000000007;
while(p != 0) {
if((p&1) == 1) { ret *= b; ret %= mod; }
b = b*b;
b %= mod;
p >>= 1;
}
return ret;
}
public static long gcd(long a, long b) {
if(a<0) return gcd(-a, b);
if(b<0) return gcd(a, -b);
return (b==0)?a:gcd(b,a%b);
}
public static long lcm(long a, long b) {
if(a<0) return lcm(-a, b);
if(b<0) return lcm(a, -b);
return a*(b/gcd(a,b));
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | ed0f9636f1cb1ebeb00ae241c77515d7 | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class solver {
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
final boolean OJ=System.getProperty("ONLINE_JUDGE")!=null;
String readString() throws IOException{
while (tok==null || !tok.hasMoreTokens()){
tok=new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws NumberFormatException, IOException{
return Integer.parseInt(readString());
}
long readLong() throws NumberFormatException, IOException{
return Long.parseLong(readString());
}
double readDouble() throws NumberFormatException, IOException{
return Double.parseDouble(readString());
}
int gcd(int a,int b){
return (b==0)?a:gcd(b,a%b);
}
long pow(int x,long n){
if (n==0)return 1;
if (n%2==1) {
return x*pow(x,n-1)%mod;
}
long b=pow(x,n/2);
return (b*b)%mod;
}
final int mod=(int)1e9+7;
void Solve() throws NumberFormatException, IOException{
int n=readInt();
int x=readInt();
int[] a=new int[n];
long sum=0;
for (int i=0;i<n;i++){
a[i]=readInt();
sum+=a[i];
}
long k=Long.MAX_VALUE;
TreeMap<Long,Integer> map=new TreeMap<Long,Integer>();
for (int i=0;i<n;i++){
long y=sum-a[i];
k=Math.min(k, y);
if (y==0) continue;
if (!map.containsKey(y)){
map.put(y, 0);
}
map.put(y, map.get(y)+1);
}
int m=0;
for (Map.Entry<Long, Integer> e:map.entrySet()){
while (k<e.getKey() && m%x==0){
k++;
m/=x;
}
if (k==e.getKey()){
m+=e.getValue();
}else{
long ans=pow(x,k)%mod;
out.println(ans);
return;
}
}
while (m!=0 && m%x==0) {
k++;
m/=x;
}
long ans=pow(x,Math.min(k, sum))%mod;
out.println(ans);
}
void Run() throws NumberFormatException, IOException{
if (OJ){
in =new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(System.out);
}else{
in=new BufferedReader(new FileReader("input.txt"));
out=new PrintWriter("output.txt");
}
long h=System.currentTimeMillis();
Solve();
// System.err.println(System.currentTimeMillis()-h);
in.close();
out.close();
}
public static void main(String[] args) throws NumberFormatException, IOException{
new solver().Run();
}
} | Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 5ad9011df5bdf90885d755e843532a3d | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.util.*; //Scanner;
public class R209_Div2_C //Name: R212_Div2_A
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int x = sc.nextInt();
int MOD = 1_000_000_007;
int[] a = new int[n];
long[] p = new long[n];
long sum = 0;
for (int i = 0; i < n; i++)
{
a[i] = sc.nextInt();
sum += a[i];
}
for (int i = 0; i < n; i++)
p[i] = sum - a[i];
Arrays.sort(p);
//Determine the number of identical exponents that sum to a higher power
//e.g. 2^2 + 2^2 = 2^3, 3^4 + 3^4 + 3^4 = 3^5
long pow = p[0];
long curPow = p[0];
int samePcnt = 1, addPow;
if (sum == 0)
{
System.out.println(1);
sc.close();
return;
}
for (int i = 1; i <= n; i++)
{
if (i < n && p[i] == curPow)
samePcnt++;
else
{
if (samePcnt > 0 && samePcnt % x == 0)
{
addPow = samePcnt / x;
pow++;
samePcnt = addPow;
i--; //look in rest of array for higher power
curPow++;
if (curPow == sum) break;
}
else
break;
}
}
long ans = GetBigPowerMod(x, pow, MOD);
System.out.println(ans);
sc.close();
}
static long GetBigPowerMod(long b, long n, int m)
{
//num will be b^n mod m; for n, m up to 1e10
long num = 1;
while (n > 0)
{
if (n % 2 == 1)
num = (num * b) % m;
b = (b * b) % m;
n /= 2;
}
return num;
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | c84dc4a76c91dc05447f80df996393e9 | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
static int power(long x,long n,long k){//快速求幂 x^n%k
long res=1;
while (n>0){
if (n%2==0){
x=(x*x)%k;
n/=2;
}else{
n--;
res=(res*x)%k;
}
}
return (int)(res%k);
}
public static void main(String arg0[]){
Scanner in=new Scanner(System.in);
int n=in.nextInt();
long x=in.nextLong();
long a[]=new long[n];
long sum=0;
for (int i=0;i<n;i++){
a[i]=in.nextLong();
sum+=a[i];
}
PriorityQueue<Long> hh=new PriorityQueue<Long>();
for (int i=0;i<n;i++){
hh.add(sum-a[i]);
}
long max=0,ge=0;
while(!hh.isEmpty()){
long s=hh.poll();
max=max>s?max:s;
ge=1;
boolean tell=true;
while (ge!=x){
if (!hh.isEmpty()){
long g=hh.poll();
if (g!=s) {tell=false;break;}
ge++;
}else{
tell=false;break;
}
}
if (tell) hh.add(s+1); else break;
}
if (max>sum) max=sum;
System.out.println(power(x, max, 1000000007));
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 34f20b821b7ae34d7b3c051fb97e2a2e | train_004.jsonl | 1383379200 | Simon has a prime number x and an array of non-negative integers a1, a2, ..., an.Simon loves fractions very much. Today he wrote out number on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: , where number t equals xa1 + a2 + ... + an. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers s and t. As GCD can be rather large, print it as a remainder after dividing it by number 1000000007 (109 + 7). | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Cf359c {
static long M = (long)1e9 + 7;
static int n;
static long x;
static long[] a = new long[101000];
static long sm = 0;
static long qp(long n, long m) {
long b = 1;
while (m != 0) {
if (m % 2 == 1) b = b*n%M;
m >>= 1;
n = n*n%M;
}
return b;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt(); x = sc.nextLong();
for (int i = 0; i < n; i++) {
a[i] = sc.nextLong();
sm += a[i];
}
for (int i = 0; i < n; i++) a[i] = sm - a[i];
a[n] = sm; n++;
Arrays.sort(a, 0, n);
long pre = a[0], ca = 0;
long ans = sm;
boolean fl = false;
for (int i = 0; i < n; i++, ca++) {
if (a[i] == pre) continue;
while (pre != a[i]) {
if (ca % x == 0) {
ca /= x;
pre++;
} else {
fl = true;
ans = pre;
break;
}
}
if (fl) break;
}
System.out.println(qp(x, ans));
}
}
| Java | ["2 2\n2 2", "3 3\n1 2 3", "2 2\n29 29", "4 5\n0 0 0 0"] | 1 second | ["8", "27", "73741817", "1"] | NoteIn the first sample . Thus, the answer to the problem is 8.In the second sample, . The answer to the problem is 27, as 351 = 13·27, 729 = 27·27.In the third sample the answer to the problem is 1073741824 mod 1000000007 = 73741817.In the fourth sample . Thus, the answer to the problem is 1. | Java 7 | standard input | [
"number theory",
"math"
] | 4867d014809bfc1d90672b32ecf43b43 | The first line contains two positive integers n and x (1 ≤ n ≤ 105, 2 ≤ x ≤ 109) — the size of the array and the prime number. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ a1 ≤ a2 ≤ ... ≤ an ≤ 109). | 1,900 | Print a single number — the answer to the problem modulo 1000000007 (109 + 7). | standard output | |
PASSED | 46b37a50040f64bdbfed57cae4139537 | train_004.jsonl | 1272294000 | You are given a 0-1 rectangular matrix. What is the number of squares in it? A square is a solid square frame (border) with linewidth equal to 1. A square should be at least 2 × 2. We are only interested in two types of squares: squares with each side parallel to a side of the matrix; squares with each side parallel to a diagonal of the matrix. For example the following matrix contains only one square of the first type: 0000000 0111100 0100100 0100100 0111100The following matrix contains only one square of the second type:00000000010000010100000100000000000Regardless of type, a square must contain at least one 1 and can't touch (by side or corner) any foreign 1. Of course, the lengths of the sides of each square should be equal.How many squares are in the given matrix? | 64 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Main {
static char[] lu = new char[]{'0','0','0','0','1','1','0','1', 0 };
static char[] ld = new char[]{'0','1', 0 ,'0','1','1','0','0','0'};
static char[] ru = new char[]{'0','0','0','1','1','0', 0 ,'1','0'};
static char[] rd = new char[]{ 0 ,'1','0','1','1','0','0','0','0'};
static char[] ude = new char[]{ 0 ,'0', 0 ,'1','1','1', 0 ,'0', 0 };
static char[] lre = new char[]{ 0 ,'1', 0 , '0' ,'1', '0' , 0 ,'1', 0 };
static char[] u = new char[]{'0','0','0','0','1','0','1','0','1'};
static char[] d = new char[]{'1','0','1','0','1','0','0','0','0'};
static char[] l = new char[]{'0','0','1','0','1','0','0','0','1'};
static char[] r = new char[]{'1','0','0','0','1','0','1','0','0'};
static char[] rdde = new char[]{'1','0','0','0','1','0','0','0','1'};
static char[] ldde = new char[]{'0','0','1','0','1','0','1','0','0'};
static boolean check(char[][] a, int i, int j, char[] c) {
return (a[i-1][j-1] ==c[0]||c[0]==0)&&(a[i-1][j]==c[1]||c[1]==0)&&(a[i-1][j+1]==c[2]||c[2]==0)&&
(a[i][j-1]==c[3]||c[3]==0)&&a[i][j] ==c[4]&&(a[i][j+1]==c[5]||c[5]==0)&&
(a[i+1][j-1]==c[6]||c[6]==0)&&(a[i+1][j]==c[7]||c[7]==0)&&(a[i+1][j+1]==c[8]||c[8]==0);
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
for(int t = s.nextInt();t>0;t--){
int n=s.nextInt();
int m=s.nextInt();
char[][] a = new char[n+2][m+2];
s.nextLine();
Arrays.fill(a[0], '0');
for(int i=0;i<n;i++){
Arrays.fill(a[i+1], '0');
char[] cs = s.nextLine().toCharArray();
for(int j=0;j<m;j++){
a[i+1][j+1]=cs[j];
}
}
Arrays.fill(a[n+1], '0');
int cnt=0;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(check(a,i,j,lu)){
int x,y;
for(x=1;check(a, i, j+x, ude)&&check(a, i+x, j, lre);x++);
for(y=1;check(a, i+y, j+x, lre)&&check(a, i+x, j+y, ude);y++);
if(x==y&&check(a, i+y, j, ld)&&check(a, i, j+x, ru)&&check(a,i+y,j+x,rd)){
cnt++;
}
}
if(check(a, i, j,u)){
int x,y;
for(x=1;check(a, i+x, j+x, rdde)&&check(a, i+x, j-x, ldde);x++);
for(y=1;check(a, i+x+y, j+x-y, ldde)&&check(a, i+x+y, j-x+y, rdde);y++);
if(x==y&&check(a, i+x, j+x, r)&&check(a, i+x, j-x, l)&&check(a, i+x+y, j, d)){
cnt++;
}
}
}
}
System.out.println(cnt);
}
}
} | Java | ["2\n8 8\n00010001\n00101000\n01000100\n10000010\n01000100\n00101000\n11010011\n11000011\n10 10\n1111111000\n1000001000\n1011001000\n1011001010\n1000001101\n1001001010\n1010101000\n1001001000\n1000001000\n1111111000", "1\n12 11\n11111111111\n10000000001\n10111111101\n10100000101\n10101100101\n10101100101\n10100000101\n10100000101\n10111111101\n10000000001\n11111111111\n00000000000"] | 2 seconds | ["1\n2", "3"] | null | Java 11 | standard input | [
"implementation"
] | 54b2a420296695edfb016b39d565e593 | The first line contains integer t (1 ≤ t ≤ 10000), where t is the number of test cases in the input. Then test cases follow. Each case starts with a line containing integers n and m (2 ≤ n, m ≤ 250), where n is the number of rows and m is the number of columns. The following n lines contain m characters each (0 or 1). The total number of characters in all test cases doesn't exceed 106 for any input file. | 2,200 | You should output exactly t lines, with the answer to the i-th test case on the i-th line. | standard output | |
PASSED | abaa82713b003ac2b0911e34251a4ae8 | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
public static void main(String args[]) throws IOException{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int mc=0;
int cc=0;
int dc=0;
for(int i=0;i<n;i++){
int m=sc.nextInt();
int c=sc.nextInt();
if(m>c)
mc++;
else if(m<c)
cc++;
else
dc++;
}
if(mc==cc)
System.out.println("Friendship is magic!^^");
else if(mc>cc && mc>dc || (mc >= n - dc))
System.out.println("Mishka");
else if(mc<cc && cc>dc|| (cc >= n - dc))
System.out.println("Chris");
}
} | Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | 97837ed5d807406e7196ec798309d131 | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m =0;
int c =0;
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
if(x>y)
m++;
else if(x<y)
c++;
}
if(m>c)
System.out.println("Mishka");
else if(c>m)
System.out.println("Chris");
else
System.out.println("Friendship is magic!^^");
}
} | Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | 47babdee9f50a8f102e84b6d8359d7f8 | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class MyClass {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int mScore = 0;
int cScore = 0;
for(int i=0; i<n;i++){
int m = sc.nextInt();
int c = sc.nextInt();
if (m == c){
continue;
}
else if(m>c){
mScore++;
}
else if (m < c){
cScore++;
}
}
if(mScore == cScore){
System.out.println("Friendship is magic!^^");
}
else if(mScore > cScore){
System.out.println("Mishka");
}
else if(mScore < cScore){
System.out.println("Chris");
}
}
} | Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | f99e16924f806be7a9ae4cec13ef0a2a | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double n = sc.nextInt();
int c1 = 0, c2 = 0;
while (n-- > 0) {
double m = sc.nextInt();
double c = sc.nextInt();
if (m > c)
c1++;
else if (c > m)
c2++;
}
if (c1 > c2)
System.out.println("Mishka");
else if (c2 > c1)
System.out.println("Chris");
else
System.out.println("Friendship is magic!^^");
}
}
| Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | d21835267363fa47bf6da20b229e76bb | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes | import java.util.*;
public class MishkaAndGame {
/**
* Creates a new instance of <code>MishkaAndGame</code>.
*/
public MishkaAndGame(){
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int n = kbd.nextInt();
int mishka = 0, chris = 0;
for (int i = 0; i < n; i++){
int m = kbd.nextInt();
int c = kbd.nextInt();
if(m > c)
mishka++;
else if(m < c)
chris++;
}
if (mishka > chris)
System.out.print("Mishka");
else if (mishka == chris)
System.out.print("Friendship is magic!^^");
else
System.out.print("Chris");
}
}
| Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | 53262ee6732f6fa777ad555cae747d96 | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes | import java.util.Scanner;
public class A0703_Mishka {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = 0;
int c = 0;
for (int i = 0; i < n; i++) {
int M = scan.nextInt();
int C = scan.nextInt();
if (M > C) m++;
if (M < C) c++;
}
if (m == c) {
System.out.println("Friendship is magic!^^");
return;
} else if (m > c) {
System.out.println("Mishka");
return;
} else System.out.println("Chris");
}
}
| Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | b2b3774906fd3d7d16bb0458dbe2aa87 | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class MishkaGame703ACodeForces {
//703A - Mishka and Game Java 8 Accepted 140 ms 20500 KB
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int round = in.nextInt();
int mishkaWin, chrisWin;
mishkaWin =0; chrisWin = 0;
for (int i=0; i < round; i++){
int mishka = in.nextInt();
int chris = in.nextInt();
if(mishka > chris){
mishkaWin++;
} else if (chris > mishka) {
chrisWin++;
}
}
if(mishkaWin > chrisWin) {
System.out.println("Mishka");
} else if(chrisWin > mishkaWin){
System.out.println("Chris");
} else {
System.out.println("Friendship is magic!^^");
}
}
}
| Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | afd0b4270a5f0c3923ac9b1b6227198c | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes | import java.util.Arrays ;
import java.util.Scanner ;
public class problemset_problem_703_A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in) ;
int n = in.nextInt();
int m =0; int c=0;
for (int i = 0; i< n; i++){
int x = in.nextInt();
int y = in.nextInt();
if (x>y){
m++;
} else if (x<y){
c++;
}
}
if (m>c){
System.out.println("Mishka");
} else if (m<c){
System.out.println("Chris");
} else {
System.out.println("Friendship is magic!^^");
}
}
}
| Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | 5c54342469625c37bae53793b3c63849 | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes |
import java.util.Scanner;
/**
*
* @author LENOVO.HDS
*/
public class MishkaAndGame {
/**
* @param args the command line arguments
*/
static Scanner sc=new Scanner(System.in);
public static void main(String[] args) {
// TODO code application logic here
int n=sc.nextInt();
int score1=0;
int score2=0;
int m;
int y;
for(int i=0;i<n;i++)
{
m=sc.nextInt();
y=sc.nextInt();
if(m>y)
{
score1+=1;
}
else if(m<y)
{
score2+=1;
}
else
{
score1+=1;
score2+=1;
}
}
if(score1>score2)
{
System.out.println("Mishka");
}
else if(score1<score2)
{
System.out.println("Chris");
}
else if(score1==score2)
{
System.out.println("Friendship is magic!^^");
}
}
}
| Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | 703d23e7626ff704fb7a9f2f95e2e49e | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes | import java.util.*;
public class MishkaAndGame {
/**
* Creates a new instance of <code>MishkaAndGame</code>.
*/
public MishkaAndGame(){
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int n = kbd.nextInt();
int mishka = 0, chris = 0;
for (int i = 0; i < n; i++){
int m = kbd.nextInt();
int c = kbd.nextInt();
if(m > c)
mishka++;
else if(m < c)
chris++;
}
if (mishka > chris)
System.out.print("Mishka");
else if (mishka == chris)
System.out.print("Friendship is magic!^^");
else
System.out.print("Chris");
}
} | Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | 8fbb6de8247ac413796d6941e8f049fd | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Code2Break
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
int n, Mishka = 0, Chris = 0, m, c;
n = scanner.nextInt();
for(int i = 0 ; i < n ; i++) {
m = scanner.nextInt();
c = scanner.nextInt();
if(m > c)
Mishka++;
else if(m < c)
Chris++;
}
if(Mishka > Chris)
System.out.println("Mishka");
else if(Mishka == Chris)
System.out.println("Friendship is magic!^^");
else
System.out.println("Chris");
}
} | Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | 6d3b519ec96966d31013097bc15c7b0b | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes |
import java.util.Scanner;
public class Mishka {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int round = input.nextInt();
int count1=0 , count2=0 ;
for(int i=1 ; i<=round ; i++)
{
int num1= input.nextInt();
int num2= input.nextInt();
if(num1>num2)
count1++;
else if(num2>num1)
count2++;
}
if(count1>count2)
System.out.print("Mishka");
else if(count1<count2)
System.out.print("Chris");
else
System.out.print("Friendship is magic!^^");
}
} | Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | 6e4a424db907dde41597d450f628ff4f | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes | import java.util.Scanner;
public class Ext {
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
int mishka,chris,n,tot_m=0,tot_c=0;
n=sc.nextInt();
for (int i = 0; i < n; i++) {
mishka=sc.nextInt();
chris=sc.nextInt();
if(mishka>chris)tot_m++;
else if (chris>mishka)tot_c++;
}
if(tot_m>tot_c)System.out.println("Mishka");
else if(tot_c>tot_m)System.out.println("Chris");
else System.out.println("Friendship is magic!^^");
}
}
| Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | bed4a03fbdab376b3d70fa7714c6a741 | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes | import java.util.*;
public class Mishka{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int[] arr = new int[a*2];
for(int i=0;i<a*2;i++){
arr[i] = scan.nextInt();
}
int sum1=0,sum2=0;
int i=0;
while(i<(a*2)-1){
if(arr[i]>arr[i+1])
sum1++;
else if(arr[i]<arr[i+1])
sum2++;
i+=2;
}
if(sum1>sum2)
System.out.println("Mishka");
else if(sum1<sum2)
System.out.println("Chris");
else
System.out.println("Friendship is magic!^^");
}
} | Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | 76263df16ad794ea40ec0744b9c309f8 | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes |
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
Scanner ss = new Scanner(System.in);
public static void main(String[] args) {
Scanner ss = new Scanner(System.in);
int x = ss.nextInt();
int y [] = new int[x];
int w [] = new int[x];
int count1=0;
int count2=0;
for (int i = 0; i < x; i++) {
y[i]=ss.nextInt();
w[i]=ss.nextInt();
if (y[i]> w[i])
count1++;
else if(y[i]< w[i])
count2++;
}
if (count1> count2)
System.out.println("Mishka");
else if (count2>count1)
System.out.println("Chris");
else
System.out.println("Friendship is magic!^^");
}
}
| Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | 90e878a879b77e27d0442eef5958e062 | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.PrintStream;
import java.util.Scanner;
/**
*
* @author USER
*/
public class JavaApplication2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner ss = new Scanner(System.in);
int x = 0;
int y = 0;
int o;
int q;
int l= ss.nextInt();
for (int i = 0 ; i < l ; i++)
{
o = ss.nextInt();
q = ss.nextInt();
if (o == q)
continue;
else if(o > q)
x++;
else
y++;
}
if (x > y)
System.out.println("Mishka");
else if (x == y)
System.out.println("Friendship is magic!^^");
else
System.out.println("Chris");
}
}
| Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output | |
PASSED | 41ca999a1d5438124a8c745a1afe8680 | train_004.jsonl | 1470323700 | Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.Rules of the game are very simple: at first number of rounds n is defined. In every round each of the players throws a cubical dice with distinct numbers from 1 to 6 written on its faces. Player, whose value after throwing the dice is greater, wins the round. In case if player dice values are equal, no one of them is a winner.In average, player, who won most of the rounds, is the winner of the game. In case if two players won the same number of rounds, the result of the game is draw.Mishka is still very little and can't count wins and losses, so she asked you to watch their game and determine its result. Please help her! | 256 megabytes | import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int m=0,c=0,i;
for(i=0;i<n;i++)
{
int a=s.nextInt();
int b=s.nextInt();
if(a>b)
{
m++;
}
else if(b>a)
c++;
}
if(m==c)
{
System.out.println("Friendship is magic!^^");
}
else if(m>c)
System.out.println("Mishka");
else
System.out.println("Chris");
}
} | Java | ["3\n3 5\n2 1\n4 2", "2\n6 1\n1 6", "3\n1 5\n3 3\n2 2"] | 1 second | ["Mishka", "Friendship is magic!^^", "Chris"] | NoteIn the first sample case Mishka loses the first round, but wins second and third rounds and thus she is the winner of the game.In the second sample case Mishka wins the first round, Chris wins the second round, and the game ends with draw with score 1:1.In the third sample case Chris wins the first round, but there is no winner of the next two rounds. The winner of the game is Chris. | Java 8 | standard input | [
"implementation"
] | 76ecde4a445bbafec3cda1fc421e6d42 | The first line of the input contains single integer n n (1 ≤ n ≤ 100) — the number of game rounds. The next n lines contains rounds description. i-th of them contains pair of integers mi and ci (1 ≤ mi, ci ≤ 6) — values on dice upper face after Mishka's and Chris' throws in i-th round respectively. | 800 | If Mishka is the winner of the game, print "Mishka" (without quotes) in the only line. If Chris is the winner of the game, print "Chris" (without quotes) in the only line. If the result of the game is draw, print "Friendship is magic!^^" (without quotes) in the only line. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.