exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
β | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
sequencelengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
β | difficulty
int64 -1
3.5k
β | prob_desc_output_spec
stringlengths 17
1.47k
β | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 46d1760a3b0b6c03dc3e8d591687f301 | train_000.jsonl | 1526308500 | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally? | 256 megabytes | import java.io.*;
import java.util.Arrays;
public class Main {
static int n, l;
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
int[] beauty = new int[3];
for(int i = 0; i < 3; ++i){
int[] numOf = new int[52];
char[] in = br.readLine().toCharArray();
l = in.length;
for(char temp : in){
int curr = (int)(temp - 'A');
if(curr > 25) curr -= 6;
++numOf[curr];
}
int max = Integer.MIN_VALUE;
for(int num : numOf) max = Math.max(max, getMax(num));
beauty[i] = max;
}
String out = "Draw";
if(beauty[0] > beauty[1] && beauty[0] > beauty[2]) out = "Kuro";
else if(beauty[1] > beauty[0] && beauty[1] > beauty[2]) out = "Shiro";
else if(beauty[2] > beauty[0] && beauty[2] > beauty[1]) out = "Katie";
System.out.println(out);
}
static int getMax(int in){
int b = in + n;
if(b > l){
if(b - l == 1 && n == 1) b = l - 1;
else b = l;
}
return b;
}
} | Java | ["3\nKuroo\nShiro\nKatie", "7\ntreasurehunt\nthreefriends\nhiCodeforces", "1\nabcabc\ncbabac\nababca", "15\nfoPaErcvJ\nmZaxowpbt\nmkuOlaHRE"] | 1 second | ["Kuro", "Shiro", "Katie", "Draw"] | NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Java 8 | standard input | [
"greedy"
] | 9b277feec7952947357b133a152fd599 | The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$)Β β the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors. | 1,800 | Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw". | standard output | |
PASSED | f7a699408438bd15e0bad01f92425adc | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static int n, a, b;
static ArrayList<Integer>[] graph;
static long[] da, db;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
a = 0;
b = Integer.parseInt(st.nextToken()) - 1;
if (b == 0) {
System.out.println(2);
return;
}
da = new long[n];
db = new long[n];
Arrays.fill(da, Long.MAX_VALUE);
Arrays.fill(db, Long.MAX_VALUE);
graph = new ArrayList[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken()) - 1;
int v = Integer.parseInt(st.nextToken()) - 1;
graph[u].add(v);
graph[v].add(u);
}
bfs(a, da);
bfs(b, db);
long ans = 0;
for (int i = 0; i < n; i++) {
if (db[i] < da[i]) {
ans = Math.max(ans, da[i]);
}
}
System.out.println(2 * ans);
}
private static void bfs(int s, long[] d) {
ArrayDeque<Integer> q = new ArrayDeque<>();
q.add(s);
d[s] = 0L;
while (!q.isEmpty()) {
int crt = q.pollFirst();
for (int v : graph[crt]) {
if (d[v] == Long.MAX_VALUE) {
d[v] = d[crt] + 1;
q.add(v);
}
}
}
}
}
| Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | ff514109d8f79ff14228974438c7db5d | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | /*Author: Satyajeet Singh, Delhi Technological University*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
public class Main {
/*********************************************Constants******************************************/
static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static long mod=(long)1e9+7;
static long mod1=998244353;
static boolean sieve[];
static ArrayList<Integer> primes;
static ArrayList<Long> factorial;
static HashSet<Integer> graph[];
/****************************************Solutions Begins*****************************************/
static boolean vis[];
static int parent[];
static HashMap<Integer,Integer>map=new HashMap<>();
static int max1=0;
static int dfs2(int start,int lev){
vis[start]=true;
max1=Math.max(max1,lev);
map.put(lev,start);
int ans=0;
for(int u:graph[start]){
if(!vis[u])
ans=Math.max(ans,dfs2(u,lev+1));
}
return ans+1;
}
static void dfs1(int start,int par,int dist[]){
parent[start]=par;
dist[start]=dist[par]+1;
vis[start]=true;
for(int u:graph[start]){
if(!vis[u]){
dfs1(u,start,dist);
}
}
}
public static void main (String[] args) throws Exception {
String st[]=br.readLine().split(" ");
int n=Integer.parseInt(st[0]);
int x=Integer.parseInt(st[1]);
Makegraph(n+1);
for(int i=0;i<n-1;i++){
st=br.readLine().split(" ");
int a=Integer.parseInt(st[0]);
int b=Integer.parseInt(st[1]);
addEdge(a,b);
addEdge(b,a);
}
int a=x;
int dist[]=new int[n+1];
vis=new boolean[n+1];
parent=new int[n+1];
dfs1(1,1,dist);
ArrayList<Integer> path=new ArrayList<>();
while(a!=1){
path.add(a);
a=parent[a];
}
Collections.reverse(path);
int point=path.get(path.size()/2);
int p1=dist[point];
vis=new boolean[n+1];
vis[parent[point]]=true;
int max=dfs2(point,0);
// debug(point,max);
// debug(path);
// debug(path);
// debug(map);
out.println(2*(dist[map.get(max1)]-1));
/****************************************Solutions Ends**************************************************/
out.flush();
out.close();
}
/****************************************Template Begins************************************************/
/***************************************Precision Printing**********************************************/
static void printPrecision(double d){
DecimalFormat ft = new DecimalFormat("0.00000000000000000");
out.println(ft.format(d));
}
/******************************************Graph*********************************************************/
static void Makegraph(int n){
graph=new HashSet[n];
for(int i=0;i<n;i++){
graph[i]=new HashSet<>();
}
}
static void addEdge(int a,int b){
graph[a].add(b);
}
/*********************************************PAIR********************************************************/
static class PairComp implements Comparator<Pair>{
public int compare(Pair p1,Pair p2){
if(p1.u>p2.u){
return 1;
}
else if(p1.u<p2.u){
return -1;
}
else{
return p1.v-p2.v;
}
}
}
static class Pair implements Comparable<Pair> {
int u;
int v;
int index=-1;
public Pair(int u, int v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
static class PairCompL implements Comparator<Pairl>{
public int compare(Pairl p1,Pairl p2){
if(p1.u>p2.u){
return 1;
}
else if(p1.u<p2.u){
return -1;
}
else{
return 0;
}
}
}
static class Pairl implements Comparable<Pair> {
long u;
long v;
int index=-1;
public Pairl(long u, long v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/*****************************************DEBUG***********************************************************/
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
/************************************MODULAR EXPONENTIATION***********************************************/
static long modulo(long a,long b,long c) {
long x=1;
long y=a;
while(b > 0){
if(b%2 == 1){
x=(x*y)%c;
}
y = (y*y)%c; // squaring the base
b /= 2;
}
return x%c;
}
/********************************************GCD**********************************************************/
static long gcd(long x, long y)
{
if(x==0)
return y;
if(y==0)
return x;
long r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
/******************************************SIEVE**********************************************************/
static void sieveMake(int n){
sieve=new boolean[n];
Arrays.fill(sieve,true);
sieve[0]=false;
sieve[1]=false;
for(int i=2;i*i<n;i++){
if(sieve[i]){
for(int j=i*i;j<n;j+=i){
sieve[j]=false;
}
}
}
primes=new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(sieve[i]){
primes.add(i);
}
}
}
/********************************************End***********************************************************/
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | cf2c97f81f9ebb9360044c4600a84162 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int x = in.nextInt() - 1;
List<Integer>[] adj = new List[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
adj[a].add(b);
adj[b].add(a);
}
int[] da = bfs(0, adj);
int[] db = bfs(x, adj);
boolean[] reachable = new boolean[n];
dfs(x, adj, da, db, reachable);
int ans = 0;
for (int i = 0; i < n; i++) {
if (reachable[i]) {
ans = Math.max(ans, da[i] * 2);
}
}
out.println(ans);
}
private void dfs(int v, List<Integer>[] adj, int[] da, int[] db, boolean[] reachable) {
reachable[v] = true;
if (da[v] == db[v]) {
return;
}
for (int u : adj[v]) {
if (!reachable[u] && db[u] <= da[u]) {
dfs(u, adj, da, db, reachable);
}
}
}
private int[] bfs(int s, List<Integer>[] adj) {
int n = adj.length;
int[] d = new int[n];
Arrays.fill(d, n + 1);
d[s] = 0;
int[] q = new int[n];
q[0] = s;
int qt = 0;
int qh = 1;
while (qt < qh) {
int v = q[qt++];
for (int u : adj[v]) {
if (d[u] > 1 + d[v]) {
d[u] = 1 + d[v];
q[qh++] = u;
}
}
}
return d;
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | 88c46dc802e1e89344d640815f2df4e0 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int[] firstEdge;
int[] edgeNxt;
int[] edgeDst;
int numEdges;
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
firstEdge = new int[n];
Arrays.fill(firstEdge, -1);
edgeNxt = new int[2 * (n - 1)];
edgeDst = new int[2 * (n - 1)];
numEdges = 0;
int x = in.nextInt() - 1;
for (int i = 0; i < n - 1; i++) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
addEdge(a, b);
addEdge(b, a);
}
int[] da = bfs(0);
int[] db = bfs(x);
boolean[] reachable = new boolean[n];
dfs(x, da, db, reachable);
int ans = 0;
for (int i = 0; i < n; i++) {
if (reachable[i]) {
ans = Math.max(ans, da[i] * 2);
}
}
out.println(ans);
}
private void addEdge(int a, int b) {
int e = numEdges++;
edgeNxt[e] = firstEdge[a];
firstEdge[a] = e;
edgeDst[e] = b;
}
private void dfs(int v, int[] da, int[] db, boolean[] reachable) {
reachable[v] = true;
if (da[v] == db[v]) {
return;
}
for (int e = firstEdge[v]; e >= 0; e = edgeNxt[e]) {
int u = edgeDst[e];
if (!reachable[u] && db[u] <= da[u]) {
dfs(u, da, db, reachable);
}
}
}
private int[] bfs(int s) {
int n = firstEdge.length;
int[] d = new int[n];
Arrays.fill(d, n + 1);
d[s] = 0;
int[] q = new int[n];
q[0] = s;
int qt = 0;
int qh = 1;
while (qt < qh) {
int v = q[qt++];
for (int e = firstEdge[v]; e >= 0; e = edgeNxt[e]) {
int u = edgeDst[e];
if (d[u] > 1 + d[v]) {
d[u] = 1 + d[v];
q[qh++] = u;
}
}
}
return d;
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | 265530eb1be592897e012529928c179d | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.util.*;
import java.io.*;
//import java.text.*;
public class Main{
final long MOD = (long)1e9+7, IINF = (long)1e19;
final int MAX = (int)1e6+10, MX = (int)1e7+1, INF = (int)1e9;
// DecimalFormat df = new DecimalFormat("0.00000000");
// final double EPS = 1e-8;
FastReader in;
PrintWriter out;
boolean multipleTC = false;
public static void main(String[] args) throws Exception{new Main().run();};
void run() throws Exception{
in = new FastReader();
out = new PrintWriter(System.out);
for(int i = 1, t = (multipleTC)?ni():1; i<=t; i++)solve(i);
out.flush();
out.close();
}
int[] dep, height;
void solve(int TC){
int n = ni();int x = ni()-1;
int[][] g = new int[n][];
int[][] edge = new int[n-1][2];
int[] cnt = new int[n];
for(int i = 0; i< n-1; i++){
edge[i] = new int[]{ni()-1, ni()-1};
cnt[edge[i][0]]++;
cnt[edge[i][1]]++;
}
for(int i =0 ;i< n; i++)g[i] = new int[cnt[i]];
for(int i = 0; i< n-1; i++){
g[edge[i][0]][--cnt[edge[i][0]]] = edge[i][1];
g[edge[i][1]][--cnt[edge[i][1]]] = edge[i][0];
}
int[] par = new int[n],d1 = new int[n], d2 = new int[n];
dfs1(g,par,d1,0,-1);
dfs2(g,d1, d2,0,-1);
int d = d1[x];
int t = (d-1)/2;
while(t>0){
x = par[x];
t--;
}
int ans = (d2[x])*2;
pn(ans);
}
void dfs1(int[][] g,int[] par,int[] d1, int u, int p){
par[u] = p;
for(int v:g[u]){
if(v==p)continue;
d1[v] = d1[u]+1;
dfs1(g,par,d1,v,u);
}
}
void dfs2(int[][] g,int[] d1,int[] d2, int u, int p){
if(g[u].length==1 && g[u][0] == p){
d2[u] = d1[u];
return;
}
for(int v:g[u]){
if(v==p)continue;
dfs2(g,d1,d2,v,u);
d2[u] = Math.max(d2[u], d2[v]);
}
}
int[] reverse(int[] a){
int[] o = new int[a.length];
for(int i = 0; i< a.length; i++)o[i] = a[a.length-i-1];
return o;
}
int[] sort(int[] a){
if(a.length==1)return a;
int mid = a.length/2;
int[] b = sort(Arrays.copyOfRange(a,0,mid)), c = sort(Arrays.copyOfRange(a,mid,a.length));
for(int i = 0, j = 0, k = 0; i< a.length; i++){
if(j<b.length && k<c.length){
if(b[j]<c[k])a[i] = b[j++];
else a[i] = c[k++];
}else if(j<b.length)a[i] = b[j++];
else a[i] = c[k++];
}
return a;
}
long[] sort(long[] a){
if(a.length==1)return a;
int mid = a.length/2;
long[] b = sort(Arrays.copyOfRange(a,0,mid)), c = sort(Arrays.copyOfRange(a,mid,a.length));
for(int i = 0, j = 0, k = 0; i< a.length; i++){
if(j<b.length && k<c.length){
if(b[j]<c[k])a[i] = b[j++];
else a[i] = c[k++];
}else if(j<b.length)a[i] = b[j++];
else a[i] = c[k++];
}
return a;
}
int[] ia(int ind,int n){
int[] out = new int[ind+n];
for(int i = 0; i< n; i++)out[ind+i] = ni();
return out;
}
long[] la(int ind, int n){
long[] out = new long[ind+n];
for(int i = 0; i< n; i++)out[ind+i] = nl();
return out;
}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bitcount(long n){return (n==0)?0:(1+bitcount(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n(){return in.next();}
String nln(){return in.nextLine();}
int ni(){return Integer.parseInt(in.next());}
long nl(){return Long.parseLong(in.next());}
double nd(){return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{
str = br.readLine();
}catch (IOException e){
e.printStackTrace();
}
return str;
}
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | 37464e494a163828ff4786dc4c3c9583 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.io.*;
import java.math.*;
import java.nio.file.attribute.AclEntry.Builder;
import java.security.KeyStore.Entry;
import java.util.*;
public class CODEFORCES {
private InputStream is;
private PrintWriter out;
int time = 0, dp[][], DP[], start[], end[], dist[], red[], black[], MOD = (int)(1e9+7), arr[];
int MAX = 200000, N, K, L;
ArrayList<Integer>[] amp;
boolean b[], boo[][];
Pair prr[], parent[][];
HashSet<Integer> hs = new HashSet<>();
public static void main(String[] args) throws Exception {
new Thread(null, new Runnable() {
public void run() {
try {
//new Main().soln();
} catch (Exception e) {
System.out.println(e);
}
}
}, "1", 1 << 26).start();
new CODEFORCES().soln();
}
char ch[][];
void solve() {
int n = ni(), x = ni()-1;
amp = (ArrayList<Integer>[]) new ArrayList[n];
for(int i = 0; i< n; i++) amp[i] = new ArrayList<>();
buildGraph(n-1);
int dist1[] = new int[n];
int dist2[] = new int[n];
dist = new int[n];
bfs(0,dist1,n);
bfs(x,dist2,n);
b = new boolean[n];
dfs(0);
int fa = 0;
for(int i = 0; i< n; i++){
//System.out.println(i+" "+dist1[i]+" "+dist2[i] +" "+dist[i]);
if(dist2[i]<dist1[i]){
fa = Math.max(fa, 2*(dist1[i]+dist[i]-1));
}
}
System.out.println(fa);
}
int dfs(int x){
b[x] = true;
int max = 0;
for(int i : amp[x]){
if(!b[i]){
max = Math.max(dfs(i), max);
}
}
return dist[x] = (1+max);
}
void bfs(int x, int dist[], int n){
dist[x] = 0;
Queue<Integer> q = new LinkedList<>();
q.add(x);
boolean b[] = new boolean[n];
b[x] = true;
while(!q.isEmpty()){
int y = q.poll();
for(int i : amp[y])
{
if(!b[i]){
dist[i] = dist[y]+1;
q.add(i);
b[i] = true;
}
}
}
}
void buildGraph(int n){
for(int i = 0; i<n ;i++){
int x = ni() -1, y = ni()- 1;
amp[x].add(y);
amp[y].add(x);
}
}
long get(int x){
long val = 0;
for(int i = 0; i< N; i++){
val += Math.abs(x-arr[i]);
x+=L;
}
return val;
}
void dfs(int i, int j){
boo[i][j] = true;
if(ch[i][j]=='F') return;
Pair p = new Pair(i,j);
if(i>0 && ch[i-1][j]!='*' && !boo[i-1][j]){
parent[i-1][j] = p;
dfs(i-1,j);
}
if(j>0 && ch[i][j-1]!='*' && !boo[i][j-1]){
parent[i][j-1] = p;
dfs(i,j-1);
}
if(i<N-1 && ch[i+1][j]!='*' && !boo[i+1][j]){
parent[i+1][j] = p;
dfs(i+1,j);
}
if(j<K-1 && ch[i][j+1]!='*' && !boo[i][j+1]){
parent[i][j+1] = p;
dfs(i,j+1);
}
}
int recur(int n){
//System.out.println(n);
if(n>=N) return 0;
if(DP[n]!=-1) return DP[n];
int ans = 0;
DP[n] = 0;
for(int i = n; i<N;i++){
if(start[arr[i]]>n){
DP[i] = Math.max((red[end[arr[i]]]^red[start[arr[i]]-1]+recur(end[arr[i]])),DP[i]);
}
/*if(start[arr[i]]>i){
ans = Math.max(ans,(red[end[arr[i]]]^red[start[arr[i]]-1]+recur(end[arr[i]])));
if(arr[i]==2){
System.out.println(i);
System.out.println((red[end[arr[i]]]^red[start[arr[i]]-1])+"*");
System.out.println(ans);
}
}*/
}
return DP[n];
}
void recur(int n, int k){
if(k<0) return;
hs.add(K-k);
if(n>=0 && dp[n][k]!=-1) return;
if(n>=0) dp[n][k] = 1;
for(int i = n+1;i<N;i++){
recur(i,k-arr[i]);
}
}
long modInverse(long a, long mOD2){
return power(a, mOD2-2, mOD2);
}
long power(long x, long y, long m)
{
if (y == 0)
return 1;
long p = power(x, y/2, m) % m;
p = (p * p) % m;
return (y%2 == 0)? p : (x * p) % m;
}
boolean isPrime(int x){
for(int i = 2;i*1L*i<=x;i++) if(x%i==0) return false;
return true;
}
public String isPossible(int b[]){
String ans = "Possible";
int n = b.length;
Arrays.sort(b);
if(n==1) return "Possible";
if(b[0]==1) return "Impossible";
if(b[0]>=n) return ans;
int lcm = 1;
for(int i : b){
long gcd = gcd(lcm,i);
lcm *= (i/gcd);
}
int cnt = 0;
for(int i : b) cnt+=lcm/i;
if(cnt>lcm) return "Impossible";
return ans;
}
public long gcd(long a, long b){
if(b==0) return a;
return gcd(b,a%b);
}
void failFn(String str, int arr[]){
int len = 0;
arr[0] = 0;
int i = 1;
while(i<arr.length){
if(str.charAt(i)==str.charAt(len)){
arr[i++] = ++len;
continue;
}
if(len == 0){
arr[i] = len;
i++;
continue;
}
if(str.charAt(i)!=str.charAt(len)){
len = arr[len-1];
}
}
}
static class ST1{
int arr[], st[], size;
ST1(int a[]){
arr = a.clone();
size = 10*arr.length;
st = new int[size];
build(0,arr.length-1,1);
}
void build(int ss, int se, int si){
if(ss==se){
st[si] = arr[ss];
return;
}
int mid = (ss+se)/2;
int val = 2*si;
build(ss,mid,val); build(mid+1,se,val+1);
st[si] = Math.min(st[val], st[val+1]);
}
int get(int ss, int se, int l, int r, int si){
if(l>se || r<ss || l>r) return Integer.MAX_VALUE;
if(l<=ss && r>=se) return st[si];
int mid = (ss+se)/2;
int val = 2*si;
return Math.min(get(ss,mid,l,r,val), get(mid+1,se,l,r,val+1));
}
}
static class ST{
int arr[],lazy[],n;
ST(int a){
n = a;
arr = new int[10*n];
lazy = new int[10*n];
}
void up(int l,int r,int val){
update(0,n-1,0,l,r,val);
}
void update(int l,int r,int c,int x,int y,int val){
if(lazy[c]!=0){
lazy[2*c+1]+=lazy[c];
lazy[2*c+2]+=lazy[c];
if(l==r)
arr[c]+=lazy[c];
lazy[c] = 0;
}
if(l>r||x>y||l>y||x>r)
return;
if(x<=l&&y>=r){
lazy[c]+=val;
return ;
}
int mid = l+r>>1;
update(l,mid,2*c+1,x,y,val);
update(mid+1,r,2*c+2,x,y,val);
arr[c] = Math.max(arr[2*c+1], arr[2*c+2]);
}
int an(int ind){
return ans(0,n-1,0,ind);
}
int ans(int l,int r,int c,int ind){
if(lazy[c]!=0){
lazy[2*c+1]+=lazy[c];
lazy[2*c+2]+=lazy[c];
if(l==r)
arr[c]+=lazy[c];
lazy[c] = 0;
}
if(l==r)
return arr[c];
int mid = l+r>>1;
if(mid>=ind)
return ans(l,mid,2*c+1,ind);
return ans(mid+1,r,2*c+2,ind);
}
}
public static class FenwickTree {
int[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates
public FenwickTree(int size) {
array = new int[size + 1];
}
public int rsq(int ind) {
assert ind > 0;
int sum = 0;
while (ind > 0) {
sum += array[ind];
//Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number
ind -= ind & (-ind);
}
return sum;
}
public int rsq(int a, int b) {
assert b >= a && a > 0 && b > 0;
return rsq(b) - rsq(a - 1);
}
public void update(int ind, int value) {
assert ind > 0;
while (ind < array.length) {
array[ind] += value;
//Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number
ind += ind & (-ind);
}
}
public int size() {
return array.length - 1;
}
}
public static int[] shuffle(int[] a, Random gen){
for(int i = 0, n = a.length;i < n;i++)
{
int ind = gen.nextInt(n-i)+i;
int d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
class Pair implements Comparable<Pair>{
int u, v;
Pair(int u, int v){
this.u = u;
this.v = v;
}public int hashCode() {
return Objects.hash();
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return ((u == other.u && v == other.v) || (v == other.u && u == other.v));
}
public int compareTo(Pair other) {
//return Integer.compare(val, other.val);
return Long.compare(u, other.u);// != 0 ? (Long.compare(u, other.u)) : (Long.compare(v,other.v));
}
}
long power(long x, long y, int mod){
long ans = 1;
while(y>0){
if(y%2==0){
x = (x*x)%mod;
y/=2;
}
else{
ans = (x*ans)%mod;
y--;
}
}
return ans;
}
void soln() {
is = System.in;
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
//out.close();
out.flush();
//tr(System.currentTimeMillis() - s + "ms");
}
// To Get Input
// Some Buffer Methods
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 | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | 6ab42f99095250bf576146ce4700b089 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.util.PriorityQueue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
public class bowwow {
private static ArrayList<Integer> arr[];
private static int n;
private static int x;
private static int max;
private static int num;
private static int mnum;
private static int calls1,calls2;
private static int count;
private static int depth[];
private static int depth2[];
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
bowwow(int n1,int x1)
{
this.n=n1;
this.x=x1;
calls1=0;calls2=0;
count=0;mnum=0;num=0;
depth=new int[n+1];
depth2=new int[n+1];
Arrays.fill(depth, 0);
Arrays.fill(depth2, 0);
depth[0]=-1;
depth2[0]=-1;
arr=new ArrayList[n+1];
int i=0;
for(i=1;i<n+1;i++)
arr[i]=new ArrayList<Integer>();
}
public static void addEdge(int v,int w)
{
arr[v].add(w);
arr[w].add(v);
}
public static void dfs(int count,int v)
{
calls1++;
depth[v]=count+1;
for(int b:arr[v])
{
if(depth[b]==0)
dfs(depth[v],b);
}
}
public static void reach (int num,int x)
{
calls2++;
depth2[x]=num+1;
for(int b:arr[x])
{
if(depth2[b]==0)
reach(depth2[x],b);
}
}
public static void main(String args[])
{
FastReader sc=new FastReader();
n=sc.nextInt();
x=sc.nextInt();
int i=0,j=0;
bowwow obj=new bowwow(n,x);
for(i=0;i<n-1;i++)
{
int p=sc.nextInt();
int q=sc.nextInt();
obj.addEdge(p,q);
}
obj.reach(0,x);
obj.dfs(0, 1);
max=0;
for( i=2;i<n+1;i++)
if(depth2[i]<depth[i] && max<depth[i] && arr[i].size()==1)
max=depth[i];
//System.out.println(calls1+ " "+calls2);
System.out.print((max-1)*2);
}
}
| Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | c853b60c7fd6d67d8797943af8557138 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | //package educational.round22;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Queue;
public class C {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), x = ni()-1;
int[] from = new int[n - 1];
int[] to = new int[n - 1];
for (int i = 0; i < n - 1; i++) {
from[i] = ni() - 1;
to[i] = ni() - 1;
}
int[][] g = packU(n, from, to);
int[][] pars = parents3(g, 0);
int[] par = pars[0], ord = pars[1], dep = pars[2];
int[][] bpars = parents3(g, x);
int[] bdep = bpars[2];
int max = 0;
Queue<Integer> q = new ArrayDeque<>();
q.add(x);
boolean[] can = new boolean[n];
can[x] = true;
while(!q.isEmpty()){
int cur = q.poll();
for(int e : g[cur]){
if(!can[e] && bdep[e] <= dep[e]){
can[e] = true;
if(bdep[e] < dep[e]){
q.add(e);
}
}
}
}
for(int i = 0;i < n;i++){
if(can[i])max = Math.max(max, dep[i]*2);
}
out.println(max);
}
public static int[][] parents3(int[][] g, int root) {
int n = g.length;
int[] par = new int[n];
Arrays.fill(par, -1);
int[] depth = new int[n];
depth[0] = 0;
int[] q = new int[n];
q[0] = root;
for (int p = 0, r = 1; p < r; p++) {
int cur = q[p];
for (int nex : g[cur]) {
if (par[cur] != nex) {
q[r++] = nex;
par[nex] = cur;
depth[nex] = depth[cur] + 1;
}
}
}
return new int[][] { par, q, depth };
}
static int[][] packU(int n, int[] from, int[] to) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int f : from)
p[f]++;
for (int t : to)
p[t]++;
for (int i = 0; i < n; i++)
g[i] = new int[p[i]];
for (int i = 0; i < from.length; i++) {
g[from[i]][--p[from[i]]] = to[i];
g[to[i]][--p[to[i]]] = from[i];
}
return g;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new C().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | a2b29e50c17000f905fad9d17a5f6e40 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class codeforces implements Runnable
{
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new codeforces(),"codeforces",1<<26).start();
}
public void run() {
InputReader s = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = s.nextInt();
int v = s.nextInt();
ArrayList<Integer>[] adj = new ArrayList[n + 1];
for(int i = 1; i <= n; i++)
adj[i] = new ArrayList<Integer>();
for(int i = 0; i < n - 1; i++) {
int n1 = s.nextInt();
int n2 = s.nextInt();
adj[n1].add(n2);
adj[n2].add(n1);
}
Queue<Integer> q = new LinkedList<Integer>();
int[] level = new int[n + 1];
Arrays.fill(level, -1);
level[1] = 0;
q.add(1);
while(!q.isEmpty()) {
int x = q.peek();
for(int i = 0; i < adj[x].size(); i++) {
int y = adj[x].get(i);
if(level[y] == -1) {
level[y] = level[x] + 1;
q.add(y);
}
}
q.remove();
}
int[] level2 = new int[n + 1];
Arrays.fill(level2, -1);
level2[v] = 0;
q.add(v);
while(!q.isEmpty()) {
int x = q.peek();
for(int i = 0; i < adj[x].size(); i++) {
int y = adj[x].get(i);
if(y == 1)
continue;
if(level2[y] == -1) {
level2[y] = level2[x] + 1;
q.add(y);
}
}
q.remove();
}
int ans = 0;
for(int i = 1; i <= n; i++) {
if(level2[i] >= 0 && level2[i] < level[i] && level[i] > ans)
ans = level[i];
}
w.println(ans * 2);
w.close();
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | ed54999ddb60c9a4174dd3df09c5df22 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class EducationalRound22C {
static int ans = -1;
static int x;
static List<ArrayList<Integer>> neighbors;
static int[] maxDepths;
public static void main(String[] args) throws Exception {
int n = readInt();
x = readInt()-1;
neighbors = new ArrayList<>();
maxDepths = new int[n];
for(int i = 0; i < n; i++){
neighbors.add(new ArrayList<>());
}
for(int i = 0; i < n-1; i++){
int a = readInt()-1;
int b = readInt()-1;
neighbors.get(a).add(b);
neighbors.get(b).add(a);
}
boolean[] visited = new boolean[n];
fillDepths(0, 0, visited);
visited = new boolean[n+1];
findX(0,0 , visited);
System.out.println(2*ans);
}
private static int findX(int id, int depth, boolean[] visited) {
if(visited[id]){
return -1;
}
visited[id] = true;
if(id == x){
ans = Math.max(ans, maxDepths[id]);
return depth;
}
int xDepth = -1;
for(int neighbor : neighbors.get(id)){
xDepth = Math.max(xDepth,findX(neighbor, depth+1, visited));
}
if(xDepth == -1){
return -1;
}
if(xDepth-depth < depth){
ans = Math.max(ans, maxDepths[id]);
}
return xDepth;
}
private static int fillDepths(int id, int depth, boolean[] visited) {
if(visited[id]){
return 0;
}
visited[id] = true;
int maxDepth = depth;
for(int neighbor : neighbors.get(id)){
maxDepth = Math.max(maxDepth,fillDepths(neighbor, depth+1, visited));
}
maxDepths[id] = maxDepth;
return maxDepth;
}
static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st = new StringTokenizer(" ");
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 | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | ca927e52fff4e3260257b1e99b7fcb01 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.lang.*;
public class TheTagGame{
public static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public char nextChar() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char)c;
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static long gcd(long a, long b){
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a*b)/gcd(a, b);
}
static long func(long a[],long size,int s){
long max1=a[s];
long maxc=a[s];
for(int i=s+1;i<size;i++){
maxc=Math.max(a[i],maxc+a[i]);
max1=Math.max(maxc,max1);
}
return max1;
}
public static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
public U x;
public V y;
public Pair(U x, V y) {
this.x = x;
this.y = y;
}
public int hashCode() {
return (x == null ? 0 : x.hashCode() * 31) + (y == null ? 0 : y.hashCode());
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair<U, V> p = (Pair<U, V>) o;
return (x == null ? p.x == null : x.equals(p.x)) && (y == null ? p.y == null : y.equals(p.y));
}
public int compareTo(Pair<U, V> b) {
int cmpU = x.compareTo(b.x);
return cmpU != 0 ? cmpU : y.compareTo(b.y);
}
public String toString() {
return String.format("(%s, %s)", x.toString(), y.toString());
}
}
static ArrayList<Integer> a[];
static int parent[];
static int height[];
static int leaf[];
static int dx[];
static int dfs(int i, int p, int h)
{
parent[i] = p;
height[i] = h;
int max = 0;
for(int j : a[i])
{
if(j == p)
{
continue;
}
int dis = dfs(j , i , h + 1);
if(dis > max)
{
max = dis;
}
}
leaf[i] = max;
return max + 1;
}
static void distance_from_x(int x, int distance)
{
dx[x] = distance;
if(parent[x] == 0)
{
return;
}
else
{
distance_from_x(parent[x], distance + 1);
}
}
public static void main(String args[])
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader sc = new FastReader(inputStream);
PrintWriter w = new PrintWriter(outputStream);
int n = sc.nextInt();
int x = sc.nextInt();
a = new ArrayList[n];
parent = new int[n];
height = new int[n];
leaf = new int[n];
dx = new int[n];
Arrays.fill(dx, n + 1);
for(int i = 0; i < n; i++)
{
a[i] = new ArrayList<>();
}
for(int i = 0; i < n - 1; i++)
{
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
a[u].add(v);
a[v].add(u);
}
dfs(0, 0, 0);
x = x - 1;
distance_from_x(x, 0);
/*for(int i = 0; i < n; i++)
{
w.print(parent[i]+" ");
}
w.println();
for(int i = 0; i < n; i++)
{
w.print(height[i]+" ");
}
w.println();
for(int i = 0; i < n; i++)
{
w.print(leaf[i]+" ");
}
w.println();
for(int i = 0; i < n; i++)
{
w.print(dx[i]+" ");
}
w.println();*/
int ans = 0, temp = 0;
for(int i = 0; i < n; i++)
{
if(height[i] > dx[i])
{
temp = height[i] + leaf[i];
}
ans = Math.max(ans, temp);
}
w.println(ans*2);
w.close();
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | 0f458bbc582ad1df0440856f42f00836 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.util.concurrent.*;
public final class tag_game
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static FastScanner sc=new FastScanner(br);
static PrintWriter out=new PrintWriter(System.out);
static Random rnd=new Random();
static int[][] al,level;
static int[] a,b,cnt;
static void dfs(int u,int dim,int p,int curr)
{
level[dim][u]=curr;
for(int x:al[u])
{
if(x!=p)
{
dfs(x,dim,u,curr+1);
}
}
}
public static void main(String args[]) throws Exception
{
int n=sc.nextInt(),x=sc.nextInt()-1;cnt=new int[n];al=new int[n][];a=new int[n];b=new int[n];
for(int i=1;i<n;i++)
{
a[i]=sc.nextInt()-1;b[i]=sc.nextInt()-1;
cnt[a[i]]++;cnt[b[i]]++;
}
for(int i=0;i<n;i++)
{
al[i]=new int[cnt[i]];cnt[i]=0;
}
level=new int[2][n];
for(int i=1;i<n;i++)
{
int u=a[i],v=b[i];
al[u][cnt[u]++]=v;al[v][cnt[v]++]=u;
}
dfs(0,0,-1,0);dfs(x,1,-1,0);int max=0;
for(int i=0;i<n;i++)
{
if(level[1][i]<level[0][i])
{
max=Math.max(max,level[0][i]*2);
}
}
out.println(max);out.close();
}
}
class FastScanner
{
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public String next() throws Exception {
return nextToken().toString();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | 2eb62b6efee89a0353932a9d36eefb34 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.io.*;
import java.util.*;
public class Edu22_C {
static ArrayList<Integer>[] adjList;
public static void main(String[] args) throws IOException {
BufferedInputStream bis = new BufferedInputStream(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(bis));
PrintWriter out = new PrintWriter(System.out);
String line;
StringTokenizer st;
while ((line = br.readLine()) != null && !line.equals("")) {
st = new StringTokenizer(line);
int nodes = Integer.parseInt(st.nextToken());
int bob = Integer.parseInt(st.nextToken()) - 1;
adjList = new ArrayList[nodes];
for (int i = 0; i < adjList.length; i++) {
adjList[i] = new ArrayList<Integer>();
}
for (int i = 0;i < nodes - 1;i++) {
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken()) - 1;
int end = Integer.parseInt(st.nextToken()) - 1;
adjList[start].add(end);
adjList[end].add(start);
}
int [] aliceTimes = new int[nodes];
int [] bobTimes = new int[nodes];
for (int i = 0;i < nodes;i++) {
aliceTimes[i] = bobTimes[i] = -2;
}
aliceTimes[0] = 0;
bobTimes[bob] = -1;
doBFS(0, aliceTimes);
doBFS(bob, bobTimes);
int ans = 0;
for (int i = 0;i < nodes;i++) {
if (aliceTimes[i] - bobTimes[i] > 1)
ans = Math.max(ans, aliceTimes[i]);
}
out.println(ans);
}
out.close();
}
public static void doBFS(int startNode, int []times) {
ArrayList<Integer> currLevel = new ArrayList<Integer>();
ArrayList<Integer> nextLevel = new ArrayList<Integer>();
currLevel.add(startNode);
while (!currLevel.isEmpty()) {
for (int currNode:currLevel) {
for (int nextNode:adjList[currNode]) {
if (times[nextNode] == -2) {
times[nextNode] = times[currNode] + 2;
nextLevel.add(nextNode);
}
}
}
currLevel = nextLevel;
nextLevel = new ArrayList<Integer>();
}
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | 84b34b57d74758878b83a3f6a6319495 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes |
import java.io.*;
import java.util.*;
import static java.lang.Math.max;
/**
* Created by Katushka on 11.03.2020.
*/
public class C {
static int[] readArray(int size, InputReader in) {
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = in.nextInt();
}
return a;
}
static long[] readLongArray(int size, InputReader in) {
long[] a = new long[size];
for (int i = 0; i < size; i++) {
a[i] = in.nextLong();
}
return a;
}
private static class Node {
int num;
List<Integer> children = new ArrayList<>();
List<Integer> path;
private final int depth;
int maxLeave;
public Node(int num, List<Integer> path, int depth) {
this.num = num;
this.path = path;
this.depth = depth;
}
}
private static int buildTree(Node node, List<Integer>[] graph, int[] visited, List<Integer> path, Node[] numToVertex, int x) {
List<Integer> connected = graph[node.num];
int res = path.size();
path.add(node.num);
for (Integer num : connected) {
if (visited[num] == 0) {
visited[num] = 1;
Node vertex = createVertex(path, num, x);
numToVertex[num] = vertex;
node.children.add(vertex.num);
vertex.maxLeave = buildTree(vertex, graph, visited, path, numToVertex, x);
res = max(res, vertex.maxLeave);
}
}
path.remove(path.size() - 1);
return res;
}
private static Node createVertex(List<Integer> path, Integer num, int x) {
List<Integer> newPath = null;
if (x == num) {
newPath = new ArrayList<>(path);
}
return new Node(num, newPath, path.size());
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = in.nextInt();
int x = in.nextInt();
List<Integer>[] edges = new List[n + 1];
for (int i = 1; i <= n; i++) {
edges[i] = new ArrayList<>();
}
for (int i = 0; i < n - 1; i++) {
int u = in.nextInt();
int v = in.nextInt();
edges[u].add(v);
edges[v].add(u);
}
Node root = new Node(1, new ArrayList<>(), 0);
int[] visited = new int[n + 1];
visited[root.num] = 1;
List<Integer> path = new ArrayList<>();
Node[] numToVertex = new Node[n + 1];
numToVertex[root.num] = root;
buildTree(root, edges, visited, path, numToVertex, x);
Node xNode = numToVertex[x];
int best = xNode.maxLeave * 2;
int i = xNode.path.size() - 1;
while (i >= 0 && i > xNode.path.size() / 2) {
Node node = numToVertex[xNode.path.get(i)];
best = max(best, node.maxLeave * 2);
i--;
}
out.println(best);
out.close();
}
private static int findMaxLeave(Integer v, Node[] numToVertex, int depth) {
int res = depth;
for (Integer child : numToVertex[v].children) {
res = max(res, findMaxLeave(child, numToVertex, depth + 1));
}
return res;
}
private static void outputArray(int[] ans, PrintWriter out) {
StringBuilder str = new StringBuilder();
for (int an : ans) {
str.append(an).append(" ");
}
out.println(str);
}
private static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextString() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public char nextChar() {
return next().charAt(0);
}
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | 751be8795f4cda585341e3b1b61e0552 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.util.*;
import java.io.*;
public class C813 {
public static void main(String args[])throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer str = new StringTokenizer(br.readLine());
int n = Integer.parseInt(str.nextToken());
int x = Integer.parseInt(str.nextToken());
Node graph[] = new Node[n];
for(int i=0; i<n; i++) {
graph[i] = new Node(i);
}
for(int i=0; i<n-1; i++) {
str = new StringTokenizer(br.readLine());
int u = Integer.parseInt(str.nextToken()) -1;
int v = Integer.parseInt(str.nextToken()) -1;
graph[u].children.add(graph[v]);
graph[v].children.add(graph[u]);
}
Integer distanceFromAlice[] = bfs(graph[0], graph);
for(Node child:graph) {
child.color = 0;
}
Integer distanceFromBob[] = bfs(graph[x-1], graph);
//System.out.println(Arrays.deepToString(distanceFromAlice));
//System.out.println(Arrays.deepToString(distanceFromBob));
int ans =0;
for(int i=0; i<n; i++) {
if(distanceFromAlice[i] > distanceFromBob[i]) {
ans = Math.max(ans, 2*distanceFromAlice[i]);
}
}
out.println(ans);
out.flush();
}
public static Integer[] bfs(Node source, Node[] graph) {
Queue<Node> list = new LinkedList<>();
Integer distance[] = new Integer[graph.length];
list.add(source);
source.color = 1;
distance[source.index] = 0;
while(!list.isEmpty()) {
Node node = list.poll();
for(Node child: node.children) {
if(child.color == 0) {
child.color =1;
list.add(child);
distance[child.index] = distance[node.index] + 1;
}
}
}
return distance;
}
}
class Node{
ArrayList<Node> children;
int color;
int index;
public Node(int index) {
children = new ArrayList<>();
color = 0;
this.index = index;
}
}
| Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | 5b7c0e71d32ef0a416ee6ae0330c5e01 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class C813_DFS {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer str = new StringTokenizer(br.readLine());
int n = Integer.parseInt(str.nextToken());
int x = Integer.parseInt(str.nextToken());
Nodes graph[] = new Nodes[n];
int distanceAlice[] = new int[n];
int distanceBob[] = new int[n];
for(int i=0; i<n; i++) {
graph[i] = new Nodes(i);
}
for(int i=0; i<n-1; i++) {
str = new StringTokenizer(br.readLine());
int v = Integer.parseInt(str.nextToken()) -1;
int u = Integer.parseInt(str.nextToken()) -1;
graph[v].children.add(graph[u]);
graph[u].children.add(graph[v]);
}
dfs(graph[0], distanceAlice);
for(int i=0; i<n; i++) {
graph[i].color = 0;
}
dfs(graph[x-1], distanceBob);
int max =0;
for(int i=0; i<n; i++) {
if(distanceAlice[i] > distanceBob[i]) {
max = Math.max(distanceAlice[i]*2, max);
}
}
out.println(max);
out.flush();
}
public static void dfs(Nodes source, int distance[]) {
if(source == null) {
return;
}
source.color = 1;
for(Nodes child:source.children) {
if(child.color ==0) {
child.color = 1;
distance[child.index] = distance[source.index] + 1;
dfs(child, distance);
}
}
}
}
class Nodes{
int color;
ArrayList<Nodes> children;
int index;
public Nodes(int index) {
color = 0;
children = new ArrayList<>();
this.index =index;
}
}
| Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | b9c96d6409d3ca382613fdef476ff454 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main{
/*
* use Integer for sorting
* avoid object comparison
* NEVER APPEND A STRING -> APPEND char by char
* Always use TreeSet instead of HashSet
*
*/
public static class FastReader {
BufferedReader br;
StringTokenizer root;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (root == null || !root.hasMoreTokens()) {
try {
root = new StringTokenizer(br.readLine());
} catch (Exception r) {
r.printStackTrace();
}
}
return root.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception r) {
r.printStackTrace();
}
return str;
}
}
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static long mod = (long) (1e9+7);
static long cf = 998244353;
static final long MAX = (long) 1e8;
public static List<Integer>[] edges;
public static int[][] parent;
public static long[] fac;
public static int N = 400000+200;
public static int x = 0;
public static boolean[] visited;
public static void main(String[] args) {
FastReader sc = new FastReader();
int n = sc.nextInt();
int t = sc.nextInt();
int a = 1;
edges = new ArrayList[n+1];
for(int i=0;i<=n;++i) edges[i] = new ArrayList<>();
for(int i=1;i<n;++i) {
int u = sc.nextInt();
int v = sc.nextInt();
edges[u].add(v);
edges[v].add(u);
}
int[] tak = new int[n+1];
int[] aok = new int[n+1];
dfs(t,0,tak);
dfs(a,0,aok);
long ans = 0;
for(int i=1;i<=n;++i) {
if(tak[i] < aok[i]) {
ans = Math.max(ans,aok[i]);
}
}
out.print(2*(ans-1));
out.close();
}
private static void dfs(int v, int parent, int[] level) {
level[v] = level[parent] + 1;
for(int child : edges[v]) {
if(child != parent) dfs(child,v,level);
}
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | cf7767e508220e2bb5c31c988de69506 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | // editorial approach
import java.util.*;
import java.io.*;
public class Main {
static final int N = (int)4e5;
static int n, B, tot, j, k;
static int[] g, pt, nt, d[];
static void link(int x, int y) {
pt[++tot] = y; nt[tot] = g[x]; g[x] = tot;
pt[++tot] = x; nt[tot] = g[y]; g[y] = tot;
}
static void dfs(int x, int fa, int tp) {
d[tp][x] = d[tp][fa] + 1;
for (int i = g[x]; i > 0; i = nt[i])
if (pt[i] != fa) dfs(pt[i], x, tp);
}
public static void main(String argv[]) {
Scanner in = new Scanner(new BufferedInputStream(System.in));
n = in.nextInt(); B = in.nextInt();
d = new int[2][n + 10];
g = new int[n + 10]; pt = new int[2 * n + 10]; nt = new int[2 * n + 10];
for (int i = 1; i < n; ++i) {
j = in.nextInt(); k = in.nextInt();
link(j, k);
}
d[0][0] = d[1][0] = -1;
dfs(1, 0, 0);
dfs(B, 0, 1);
int ans = 0;
for (int i = 1; i <= n; ++i) if (d[1][i] < d[0][i] && d[0][i] > ans) ans = d[0][i];
System.out.printf("%d\n", ans << 1);
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | 35be9a3aa5fcd3c720f7180a738a8fa7 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.io.*;
import java.util.*;
public class TheTagGame {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader inp = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
solver.solve(inp, out);
out.close();
}
static class Solver {
int[][] g;
int[] depths;
int[] prev;
boolean[] visited;
int x, depth;
private void dfs(int node, int depth) {
if (visited[node]) return;
if (node == x) this.depth = depth;
visited[node] = true;
depths[node] = depth;
for (int neigh: g[node]) {
if (!visited[neigh]) prev[neigh] = node;
dfs(neigh, depth + 1);
}
}
private int dfs2(int node, int max) {
int temp = 0;
for (int neigh: g[node]) {
if (depths[neigh] > depths[node]) {
temp = Math.max(temp, dfs2(neigh, max + 1));
}
}
return Math.max(max, temp);
}
private void solve(InputReader inp, PrintWriter out) {
int n = inp.nextInt();
x = inp.nextInt() - 1;
visited = new boolean[n];
prev = new int[n];
g = graph(inp, n, n - 1, true,true);
depths = new int[n];
dfs(0, 0);
int between = depth - 1;
int res = (between >> 1) << 1;
if ((between & 1) == 1) res += 4;
else res += 2;
int i = between >> 1;
while (i-- > 0) x = prev[x];
res += dfs2(x, 0) << 1;
out.println(res);
}
}
private static int[][] graph(InputReader inp, int n, int m, boolean undirected, boolean reduce) {
int[][] g = new int[n][];
int[][] edges = new int[m][2];
int[] out_degree = new int[n];
int[] cnt = new int[n];
for (int i = 0; i < m; i++) {
edges[i][0] = inp.nextInt();
edges[i][1] = inp.nextInt();
if (reduce) {
edges[i][0]--;
edges[i][1]--;
}
out_degree[edges[i][0]]++;
if (undirected) out_degree[edges[i][1]]++;
}
for (int i = 0; i < n; i++) g[i] = new int[out_degree[i]];
for (int[] edge: edges) {
g[edge[0]][cnt[edge[0]]++] = edge[1];
if (undirected) g[edge[1]][cnt[edge[1]]++] = edge[0];
}
return g;
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | d9cb107bbdcc7de836888a517be77f03 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.io.*;
import java.util.*;
public class TheTagGame {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader inp = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
solver.solve(inp, out);
out.close();
}
static class Solver {
int[][] g;
int[] depths;
int[] prev;
boolean[] visited;
int x, depth;
private void dfs(int node, int depth) {
if (visited[node]) return;
if (node == x) this.depth = depth;
visited[node] = true;
depths[node] = depth;
for (int neigh: g[node]) {
if (!visited[neigh]) prev[neigh] = node;
dfs(neigh, depth + 1);
}
}
private int dfs2(int node, int max) {
int temp = 0;
for (int neigh: g[node]) {
if (depths[neigh] > depths[node]) {
//System.out.println("from " + (node+1) + " to " + (neigh+1) + " depth " + max);
temp = Math.max(temp, dfs2(neigh, max + 1));
}
}
return Math.max(max, temp);
}
private void solve(InputReader inp, PrintWriter out) {
/*
DFS until x is reached:
- keep track of depth
- keep track of path
- go back (depth - 1) / 2 steps to y
DFS from y:
- calculate max depth path from y
- add max depth * 2
- if nodes between 1 and x is odd: add 4
- if nodes between 1 and x is even: add 2
*/
int n = inp.nextInt();
x = inp.nextInt() - 1;
visited = new boolean[n];
prev = new int[n];
g = graph(inp, n, n - 1, true,true);
depths = new int[n];
int res = 0;
dfs(0, 0);
int between = depth - 1;
res += between / 2 * 2; //move up moves
if ((between & 1) == 1) res += 4; //moves to reach
else res += 2; //moves to reach
//move up
int i = between >> 1;
while (i-- > 0) x = prev[x];
//out.println("start: " + (x+1));
int longestPath = dfs2(x, 0);
//out.println("longest path " + longestPath);
//out.println("depth 3 " + depths[2]);
//out.println("depth 2 " + depths[1]);
res += longestPath << 1;
out.println(res);
}
}
private static int[][] graph(InputReader inp, int n, int m, boolean undirected, boolean reduce) {
int[][] g = new int[n][];
int[][] edges = new int[m][2];
int[] out_degree = new int[n];
int[] cnt = new int[n];
for (int i = 0; i < m; i++) {
edges[i][0] = inp.nextInt();
edges[i][1] = inp.nextInt();
if (reduce) {
edges[i][0]--;
edges[i][1]--;
}
out_degree[edges[i][0]]++;
if (undirected) out_degree[edges[i][1]]++;
}
for (int i = 0; i < n; i++) g[i] = new int[out_degree[i]];
for (int[] edge: edges) {
g[edge[0]][cnt[edge[0]]++] = edge[1];
if (undirected) g[edge[1]][cnt[edge[1]]++] = edge[0];
}
return g;
}
private static void printGraph(int[][] g, boolean reduced) {
for (int i = 0; i < g.length; i++) {
System.out.print(reduced?(i+1)+": ":i + ": ");
for (int j = 0; j < g[i].length; j++) {
System.out.print(reduced?(g[i][j]+1)+" ":g[i][j]+" ");
} System.out.print("\n");
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | c166cc8eed64f6a9637a286d55e3f635 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
new Main().run(in, out);
out.close();
}
int N;
int B;
List<Integer>[] adj;
void run(FastScanner in, PrintWriter out) {
// dfs
// on the way down get dist from S
// on the way up get dist from B (root), and also max depth
// at each intersection, if b can reach the intersection from
// before S can reach the intersection, B can travel to the
// max depth leaf of the subtree rooted at the intersection
N = in.nextInt();
B = in.nextInt();
bDist = new int[N+1];
adj = new List[N+1];
for (int i = 1; i <= N; i++) adj[i] = new ArrayList<>();
for (int i = 1; i < N; i++) {
int u = in.nextInt();
int v = in.nextInt();
adj[u].add(v);
adj[v].add(u);
}
// dfs from B to get distances
// then dfs from root to get answer
dfsB(B, -1, 0);
dfs(1, -1, 0);
out.println(ans*2);
}
int[] bDist;
void dfsB(int u, int p, int d) {
bDist[u] = d;
for (int v : adj[u]) {
if (v == p) continue;
dfsB(v, u, d+1);
}
}
int ans = 0;
// returns max leaf dist
int dfs(int u, int p, int d) {
int maxDist = 0;
for (int v : adj[u]) {
if (v == p) continue;
maxDist = Math.max(maxDist, dfs(v, u, d+1));
}
// if B can reach here before S can
if (bDist[u] < d) {
// b runs here first then goes to the deepest leaf in the
// subtree
// s goes from root to leaf
ans = Math.max(d+maxDist, ans);
}
return maxDist+1;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = null;
}
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());
}
}
}
| Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | aa6c1e37222cf524936e4efd365c4cec | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | /*
ID: mchensd
LANG: JAVA
PROG: TheTagGame
*/
/**
*
* @author Michael
*/
import java.util.*;
import java.io.*;
public class TheTagGame {
static int m;
static int[] maxPath;
static int[] abPath;
static int pathInd, finalPathInd;
static boolean found = false;
public static class Tree {
int V;
ArrayList<Integer>[] adj;
public Tree(int V) {
this.V = V;
adj = (ArrayList<Integer>[]) new ArrayList[V];
for (int i=0; i<V; ++i) {
adj[i] = new ArrayList<>();
}
}
public void addEdge(int v1, int v2) {
adj[v1].add(v2);
adj[v2].add(v1);
}
}
public static int dfs(Tree t, int v, int from) {
if (t.adj[v].size() == 1 && t.adj[v].get(0) == from) return 0;
for (int n : t.adj[v]) {
if (n != from) {
if (!found) {
abPath[pathInd] = n;
finalPathInd = pathInd;
if (n == m) found = true;
}
if (!found) {
++pathInd;
maxPath[v] = Math.max(maxPath[v], 1 + dfs(t, n, v));
--pathInd;
}
else maxPath[v] = Math.max(maxPath[v], 1 + dfs(t, n, v));
}
}
return maxPath[v];
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
maxPath = new int[n+1];
abPath = new int[n+1];
abPath[0] = 1;
Tree t = new Tree(n+1);
for (int i=0; i<n-1; ++i) {
st = new StringTokenizer(br.readLine());
t.addEdge(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
}
pathInd = 1;
finalPathInd = 1;
dfs(t, 1, 1);
// System.out.println(Arrays.toString(abPath));
// System.out.println(Arrays.toString(maxPath));
// System.out.println(max);
int back = ((finalPathInd+1) / 2) - 1;
// System.out.println(back);
// System.out.println(finalPathInd);
// System.out.println(maxPath[2]);
int longest = maxPath[abPath[finalPathInd-back]] + finalPathInd-back;
pw.println(longest*2);
pw.close();
}
}
| Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | e22d51f84705b17f3a49576405f9fe9a | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class C {
static int N, X;
static ArrayList<Integer>[] g;
static int[] level, reach, p;
static int dfs(int u, int par, int depth) {
p[u] = par;
level[u] = depth;
int max = level[u];
for (int v : g[u])
if (v != par)
max = Math.max(max, dfs(v, u, depth + 1));
reach[u] = max;
return max;
}
public static void main(String[] args) throws IOException {
MyScanner sc = new MyScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
N = sc.nextInt();
X = sc.nextInt() - 1;
g = new ArrayList[N];
for (int i = 0; i < N; i++)
g[i] = new ArrayList<>();
for (int i = 0; i < N - 1; i++) {
int u = sc.nextInt() - 1, v = sc.nextInt() - 1;
g[u].add(v);
g[v].add(u);
}
level = new int[N];
reach = new int[N];
p = new int[N];
dfs(0, -1, 0);
if (level[X] - level[0] == 1)
out.println(reach[X] << 1);
else {
int up = (level[X] - level[0]) >> 1, node = X, max = reach[X];
if (((level[X] - level[0]) & 1) == 0)
up--;
while (up-- > 0 && p[node] != -1) {
node = p[node];
max = Math.max(max, reach[node]);
}
out.println(max << 1);
}
out.flush();
out.close();
}
static class MyScanner {
StringTokenizer st;
BufferedReader br;
public MyScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public MyScanner(String file) throws IOException {
br = new BufferedReader(new FileReader(new File(file)));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | 4a2d9477a2fed58f0d1a133c6d7972c3 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.util.*;
import javax.swing.Painter;
import java.io.*;
public class C {
FastScanner in;
PrintWriter out;
boolean systemIO = true;
public static class Pair implements Comparable<Pair> {
int x;
int y;
public Pair(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
// TODO Auto-generated method stub
return x - o.x;
}
}
public static void quickSort(long[] a, int from, int to) {
if (to - from <= 1) {
return;
}
int i = from;
int j = to - 1;
long x = a[from + (new Random()).nextInt(to - from)];
while (i <= j) {
while (a[i] < x) {
i++;
}
while (a[j] > x) {
j--;
}
if (i <= j) {
long t = a[i];
a[i] = a[j];
a[j] = t;
i++;
j--;
}
}
quickSort(a, from, j + 1);
quickSort(a, j + 1, to);
}
public void dfs(int v, int h) {
used[v] = true;
d1[v] = h;
for (int i : a[v]) {
if (!used[i]) {
dfs(i, h + 1);
}
}
}
public void dfs1(int v, int h) {
used[v] = true;
ans = Math.max(d1[v], ans);
for (int i : a[v]) {
if (!used[i] && h + 1 < d1[i]) {
dfs1(i, h + 1);
}
}
}
int x;
ArrayList<Integer>[] a;
boolean[] used;
int[] d1;
int ans = 0;
public void solve() throws IOException {
int n = in.nextInt();
x = in.nextInt() - 1;
a = new ArrayList[n];
for (int i = 0; i < a.length; i++) {
a[i] = new ArrayList<>();
}
d1 = new int[n];
used = new boolean[n];
for (int i = 0; i < a.length - 1; i++) {
int y = in.nextInt() - 1;
int z = in.nextInt() - 1;
a[y].add(z);
a[z].add(y);
}
dfs(0, 0);
used = new boolean[n];
dfs1(x, 0);
System.out.println(2 * ans);
}
public void run() throws IOException {
if (systemIO) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
in = new FastScanner(new File("input.txt"));
out = new PrintWriter(new File("output.txt"));
}
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
public static void main(String[] arg) throws IOException {
new C().run();
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | b7666fedb9acbb21c753d0b13bba5605 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class M
{
/*int x,y;
public TestClass(int x,int y)
{
this.x=x;
this.y=y;
}*/
public static void main(String args[]) throws Exception
{
//Scanner scan=new Scanner(System.in);
InputReader hb=new InputReader(System.in);
PrintWriter w=new PrintWriter(System.out);
int n=hb.nextInt();
int x=hb.nextInt();
ArrayList<Integer> list[]=new ArrayList[n+1];
for(int i=1;i<=n;i++)
list[i]=new ArrayList<Integer>();
int d1[]=new int[n+1];
int dx[]=new int[n+1];
for(int i=0;i<n-1;i++)
{
int u=hb.nextInt();
int v=hb.nextInt();
list[u].add(v);
list[v].add(u);
}
int visit1[]=new int[n+1];
int visitx[]=new int[n+1];
dfs(list,d1,visit1,1,0);
dfs(list,dx,visitx,x,0);
int ans=0;
for(int i=0;i<=n;i++)
{
//w.println(d1[i]+" "+dx[i]);
if(d1[i]>dx[i] && ans<2*d1[i])
ans=2*d1[i];
}
w.print(ans);
//w.print("DONE");
w.close();
}
private static void dfs(ArrayList<Integer>[] list,int []d,int[] visit,int s,int l)
{
//System.out.println("@@");
d[s]=l;
visit[s]++;
for(int i:list[s])
{
if(visit[i] == 0)
{
dfs(list,d,visit,i,l+1);
}
}
}
private void shuffle(int[] arr)
{
Random ran = new Random();
for (int i = 0; i < arr.length; i++) {
int i1 = ran.nextInt(arr.length);
int i2 = ran.nextInt(arr.length);
int temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
}
static class DSU
{
int parent[];
int sizeParent[];
DSU(int n)
{
parent=new int[n];
sizeParent=new int[n];
Arrays.fill(sizeParent,1);
for(int i=0;i<n;i++)
parent[i]=i;
}
int find(int x)
{
if(x!=parent[x])
parent[x]=find(parent[x]);
return parent[x];
}
void union(int x,int y)
{
x=find(x);
y=find(y);
if(sizeParent[x]>=sizeParent[y])
{
if(x!=y)
sizeParent[x]+=sizeParent[y];
parent[y]=x;
}
else
{
if(x!=y)
sizeParent[y]+=sizeParent[x];
parent[x]=y;
}
}
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
static class Pair implements Comparable<Pair>
{
int a;
int b;
String str;
public Pair(int a,int b)
{
this.a=a;
this.b=b;
str=min(a,b)+" "+max(a,b);
}
public int compareTo(Pair pair)
{
if(Integer.compare(a,pair.a)==0)
return Integer.compare(b,pair.b);
return Integer.compare(a,pair.a);
}
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | 9a4b3612f7442105880ca354a066711b | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes | import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class TestClass //implements Runnable
{
/*int x,y;
public TestClass(int x,int y)
{
this.x=x;
this.y=y;
}*/
public static void main(String args[]) throws Exception
{/*
new Thread(null, new TestClass(),"TESTCLASS",1<<23).start();
}
public void run()
{*/
//Scanner scan=new Scanner(System.in);
InputReader hb=new InputReader(System.in);
PrintWriter w=new PrintWriter(System.out);
int n=hb.nextInt();
int x=hb.nextInt();
ArrayList<Integer> list[]=new ArrayList[n+1];
for(int i=1;i<=n;i++)
list[i]=new ArrayList<Integer>();
int d1[]=new int[n+1];
int dx[]=new int[n+1];
for(int i=0;i<n-1;i++)
{
int u=hb.nextInt();
int v=hb.nextInt();
list[u].add(v);
list[v].add(u);
}
boolean visit1[]=new boolean[n+1];
boolean visitx[]=new boolean[n+1];
dfs(list,d1,visit1,1,0);
dfs(list,dx,visitx,x,0);
int ans=0;
for(int i=0;i<=n;i++)
{
//w.println(d1[i]+" "+dx[i]);
if(d1[i]>dx[i] && ans<2*d1[i])
ans=2*d1[i];
}
w.print(ans);
//w.print("DONE");
w.close();
}
private static void dfs(ArrayList<Integer>[] list,int []d,boolean[] visit,int s,int l)
{
//System.out.println("@@");
if(visit[s])
return;
d[s]=l;
visit[s]=true;
for(int i:list[s])
{
if(!visit[i])
{
dfs(list,d,visit,i,l+1);
}
}
}
private void shuffle(int[] arr)
{
Random ran = new Random();
for (int i = 0; i < arr.length; i++) {
int i1 = ran.nextInt(arr.length);
int i2 = ran.nextInt(arr.length);
int temp = arr[i1];
arr[i1] = arr[i2];
arr[i2] = temp;
}
}
static class DSU
{
int parent[];
int sizeParent[];
DSU(int n)
{
parent=new int[n];
sizeParent=new int[n];
Arrays.fill(sizeParent,1);
for(int i=0;i<n;i++)
parent[i]=i;
}
int find(int x)
{
if(x!=parent[x])
parent[x]=find(parent[x]);
return parent[x];
}
void union(int x,int y)
{
x=find(x);
y=find(y);
if(sizeParent[x]>=sizeParent[y])
{
if(x!=y)
sizeParent[x]+=sizeParent[y];
parent[y]=x;
}
else
{
if(x!=y)
sizeParent[y]+=sizeParent[x];
parent[x]=y;
}
}
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
static class Pair implements Comparable<Pair>
{
int a;
int b;
String str;
public Pair(int a,int b)
{
this.a=a;
this.b=b;
str=min(a,b)+" "+max(a,b);
}
public int compareTo(Pair pair)
{
if(Integer.compare(a,pair.a)==0)
return Integer.compare(b,pair.b);
return Integer.compare(a,pair.a);
}
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | 335826b5d64170f0a4f359d9cf89a9fd | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main {
private static Scanner sc;
private static Printer pr;
static long aLong=(long )1e9+7;
static long Mod=998244353;
static TreeSet<Integer>[]list;
static int []distanceX;
static int []distanceRoot;
static boolean[]visRoot;
static boolean[]visX;
private static void solve() throws IOException {
//in the name of god
// you are anything and we are nothing
int n=sc.nextInt(),x=sc.nextInt();
list=new TreeSet[n+1];
distanceRoot=new int[n+1];
distanceX=new int[n+1];
for (int i=1;i<=n;++i)
list[i]=new TreeSet<>();
for (int i=1;i<=n-1;++i){
int u=sc.nextInt(),v=sc.nextInt();
list[u].add(v);
list[v].add(u);
}
visRoot=new boolean[n+1];
visX=new boolean[n+1];
dfs_1(1,0);
dfs_2(x,0);
int ans=0;
for (int i=1;i<=n;++i){
if (distanceRoot[i]>distanceX[i])
ans=Math.max(distanceRoot[i]<<1,ans);
}
pr.println(ans);
}
public static void dfs_1(int src,int lev){
if (visRoot[src])
return;
distanceRoot[src]=lev;
visRoot[src]=true;
for (int v:list[src]){
if (!visRoot[v])
dfs_1(v,lev+1);
}
}
public static void dfs_2(int src,int lev){
if (visX[src])
return;
distanceX[src]=lev;
visX[src]=true;
for (int v:list[src]){
if (!visX[v])
dfs_2(v,lev+1);
}
}
public static int[] radixSort(int[] f) {
int[] to = new int[f.length];
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++) b[1 + (f[i] & 0xffff)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < f.length; i++) to[b[f[i] & 0xffff]++] = f[i];
int[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++) b[1 + (f[i] >>> 16)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < f.length; i++) to[b[f[i] >>> 16]++] = f[i];
int[] d = f;
f = to;
to = d;
}
return f;
}
public static long []primeFactor(int n){
long []prime=new long[n+1];
prime[1]=1;
for (int i=2;i<=n;i++)
prime[i]=((i&1)==0)?2:i;
for (int i=3;i*i<=n;i++){
if (prime[i]==i){
for (int j=i*i;j<=n;j+=i){
if (prime[j]==j)
prime[j]=i;
}
}
}
return prime;
}
public static long gcd(long a,long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
public static void main(String[] args) throws IOException {
sc = new Scanner(System.in);
pr = new Printer(System.out);
solve();
pr.close();
// sc.close();
}
private static class Scanner {
BufferedReader br;
Scanner (InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
private boolean isPrintable(int ch) {
return ch >= '!' && ch <= '~';
}
private boolean isCRLF(int ch) {
return ch == '\n' || ch == '\r' || ch == -1;
}
private int nextPrintable() {
try {
int ch;
while (!isPrintable(ch = br.read())) {
if (ch == -1) {
throw new NoSuchElementException();
}
}
return ch;
} catch (IOException e) {
throw new NoSuchElementException();
}
}
String next() {
try {
int ch = nextPrintable();
StringBuilder sb = new StringBuilder();
do {
sb.appendCodePoint(ch);
} while (isPrintable(ch = br.read()));
return sb.toString();
} catch (IOException e) {
throw new NoSuchElementException();
}
}
int nextInt() {
try {
// parseInt from Integer.parseInt()
boolean negative = false;
int res = 0;
int limit = -Integer.MAX_VALUE;
int radix = 10;
int fc = nextPrintable();
if (fc < '0') {
if (fc == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (fc != '+') {
throw new NumberFormatException();
}
fc = br.read();
}
int multmin = limit / radix;
int ch = fc;
do {
int digit = ch - '0';
if (digit < 0 || digit >= radix) {
throw new NumberFormatException();
}
if (res < multmin) {
throw new NumberFormatException();
}
res *= radix;
if (res < limit + digit) {
throw new NumberFormatException();
}
res -= digit;
} while (isPrintable(ch = br.read()));
return negative ? res : -res;
} catch (IOException e) {
throw new NoSuchElementException();
}
}
long nextLong() {
try {
// parseLong from Long.parseLong()
boolean negative = false;
long res = 0;
long limit = -Long.MAX_VALUE;
int radix = 10;
int fc = nextPrintable();
if (fc < '0') {
if (fc == '-') {
negative = true;
limit = Long.MIN_VALUE;
} else if (fc != '+') {
throw new NumberFormatException();
}
fc = br.read();
}
long multmin = limit / radix;
int ch = fc;
do {
int digit = ch - '0';
if (digit < 0 || digit >= radix) {
throw new NumberFormatException();
}
if (res < multmin) {
throw new NumberFormatException();
}
res *= radix;
if (res < limit + digit) {
throw new NumberFormatException();
}
res -= digit;
} while (isPrintable(ch = br.read()));
return negative ? res : -res;
} catch (IOException e) {
throw new NoSuchElementException();
}
}
float nextFloat() {
return Float.parseFloat(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
try {
int ch;
while (isCRLF(ch = br.read())) {
if (ch == -1) {
throw new NoSuchElementException();
}
}
StringBuilder sb = new StringBuilder();
do {
sb.appendCodePoint(ch);
} while (!isCRLF(ch = br.read()));
return sb.toString();
} catch (IOException e) {
throw new NoSuchElementException();
}
}
void close() {
try {
br.close();
} catch (IOException e) {
// throw new NoSuchElementException();
}
}
}
private static class Printer extends PrintWriter {
Printer(PrintStream out) {
super(out);
}
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | ddd5551853d6a4a9bc60d62b854c9ef2 | train_000.jsonl | 1496675100 | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.Alice starts at vertex 1 and Bob starts at vertex x (xββ β1). The moves are made in turns, Bob goes first. In one move one can either stay at the current vertex or travel to the neighbouring one.The game ends when Alice goes to the same vertex where Bob is standing. Alice wants to minimize the total number of moves and Bob wants to maximize it.You should write a program which will determine how many moves will the game last. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main {
private static Scanner sc;
private static Printer pr;
static long aLong=(long )1e9+7;
static long Mod=998244353;
static TreeSet<Integer>[]list;
static int []distanceX;
static int []distanceRoot;
private static void solve() throws IOException {
//in the name of god
// you are anything and we are nothing
int n=sc.nextInt(),x=sc.nextInt();
list=new TreeSet[n+1];
distanceRoot=new int[n+1];
distanceX=new int[n+1];
for (int i=1;i<=n;++i)
list[i]=new TreeSet<>();
for (int i=1;i<=n-1;++i){
int u=sc.nextInt(),v=sc.nextInt();
list[u].add(v);
list[v].add(u);
}
boolean []visRoot=new boolean[n+1];
boolean []visX=new boolean[n+1];
dfs(distanceRoot,visRoot,1,0);
dfs(distanceX,visX,x,0);
int ans=0;
for (int i=1;i<=n;++i){
if (distanceRoot[i]>distanceX[i])
ans=Math.max(distanceRoot[i]<<1,ans);
}
pr.println(ans);
}
public static void dfs(int []distance,boolean []vis,int src,int lev){
if (vis[src])
return;
distance[src]=lev;
vis[src]=true;
for (int v:list[src]){
if (!vis[v])
dfs(distance,vis,v,lev+1);
}
}
public static int[] radixSort(int[] f) {
int[] to = new int[f.length];
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++) b[1 + (f[i] & 0xffff)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < f.length; i++) to[b[f[i] & 0xffff]++] = f[i];
int[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++) b[1 + (f[i] >>> 16)]++;
for (int i = 1; i <= 65536; i++) b[i] += b[i - 1];
for (int i = 0; i < f.length; i++) to[b[f[i] >>> 16]++] = f[i];
int[] d = f;
f = to;
to = d;
}
return f;
}
public static long []primeFactor(int n){
long []prime=new long[n+1];
prime[1]=1;
for (int i=2;i<=n;i++)
prime[i]=((i&1)==0)?2:i;
for (int i=3;i*i<=n;i++){
if (prime[i]==i){
for (int j=i*i;j<=n;j+=i){
if (prime[j]==j)
prime[j]=i;
}
}
}
return prime;
}
public static long gcd(long a,long b) {
if (a == 0) return b;
return gcd(b % a, a);
}
public static void main(String[] args) throws IOException {
sc = new Scanner(System.in);
pr = new Printer(System.out);
solve();
pr.close();
// sc.close();
}
private static class Scanner {
BufferedReader br;
Scanner (InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
private boolean isPrintable(int ch) {
return ch >= '!' && ch <= '~';
}
private boolean isCRLF(int ch) {
return ch == '\n' || ch == '\r' || ch == -1;
}
private int nextPrintable() {
try {
int ch;
while (!isPrintable(ch = br.read())) {
if (ch == -1) {
throw new NoSuchElementException();
}
}
return ch;
} catch (IOException e) {
throw new NoSuchElementException();
}
}
String next() {
try {
int ch = nextPrintable();
StringBuilder sb = new StringBuilder();
do {
sb.appendCodePoint(ch);
} while (isPrintable(ch = br.read()));
return sb.toString();
} catch (IOException e) {
throw new NoSuchElementException();
}
}
int nextInt() {
try {
// parseInt from Integer.parseInt()
boolean negative = false;
int res = 0;
int limit = -Integer.MAX_VALUE;
int radix = 10;
int fc = nextPrintable();
if (fc < '0') {
if (fc == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (fc != '+') {
throw new NumberFormatException();
}
fc = br.read();
}
int multmin = limit / radix;
int ch = fc;
do {
int digit = ch - '0';
if (digit < 0 || digit >= radix) {
throw new NumberFormatException();
}
if (res < multmin) {
throw new NumberFormatException();
}
res *= radix;
if (res < limit + digit) {
throw new NumberFormatException();
}
res -= digit;
} while (isPrintable(ch = br.read()));
return negative ? res : -res;
} catch (IOException e) {
throw new NoSuchElementException();
}
}
long nextLong() {
try {
// parseLong from Long.parseLong()
boolean negative = false;
long res = 0;
long limit = -Long.MAX_VALUE;
int radix = 10;
int fc = nextPrintable();
if (fc < '0') {
if (fc == '-') {
negative = true;
limit = Long.MIN_VALUE;
} else if (fc != '+') {
throw new NumberFormatException();
}
fc = br.read();
}
long multmin = limit / radix;
int ch = fc;
do {
int digit = ch - '0';
if (digit < 0 || digit >= radix) {
throw new NumberFormatException();
}
if (res < multmin) {
throw new NumberFormatException();
}
res *= radix;
if (res < limit + digit) {
throw new NumberFormatException();
}
res -= digit;
} while (isPrintable(ch = br.read()));
return negative ? res : -res;
} catch (IOException e) {
throw new NoSuchElementException();
}
}
float nextFloat() {
return Float.parseFloat(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
try {
int ch;
while (isCRLF(ch = br.read())) {
if (ch == -1) {
throw new NoSuchElementException();
}
}
StringBuilder sb = new StringBuilder();
do {
sb.appendCodePoint(ch);
} while (!isCRLF(ch = br.read()));
return sb.toString();
} catch (IOException e) {
throw new NoSuchElementException();
}
}
void close() {
try {
br.close();
} catch (IOException e) {
// throw new NoSuchElementException();
}
}
}
private static class Printer extends PrintWriter {
Printer(PrintStream out) {
super(out);
}
}
} | Java | ["4 3\n1 2\n2 3\n2 4", "5 2\n1 2\n2 3\n3 4\n2 5"] | 1 second | ["4", "6"] | NoteIn the first example the tree looks like this: The red vertex is Alice's starting position, the blue one is Bob's. Bob will make the game run the longest by standing at the vertex 3 during all the game. So here are the moves:B: stay at vertex 3A: go to vertex 2B: stay at vertex 3A: go to vertex 3In the second example the tree looks like this: The moves in the optimal strategy are:B: go to vertex 3A: go to vertex 2B: go to vertex 4A: go to vertex 3B: stay at vertex 4A: go to vertex 4 | Java 8 | standard input | [
"dfs and similar",
"graphs"
] | 0cb9a20ca0a056b86885c5bcd031c13f | The first line contains two integer numbers n and x (2ββ€βnββ€β2Β·105, 2ββ€βxββ€βn). Each of the next nβ-β1 lines contains two integer numbers a and b (1ββ€βa,βbββ€βn) β edges of the tree. It is guaranteed that the edges form a valid tree. | 1,700 | Print the total number of moves Alice and Bob will make. | standard output | |
PASSED | a28d88de4e1263bfd98fe7cceed624e7 | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class CF177C {
static List<Set<Integer>> groups = new ArrayList<>();
static List<Boolean> groupHasDislikes = new ArrayList<>();
static Map<Integer, Integer> groupOfPerson = new HashMap<>();
public static int getOrCreateGroupId(int person) {
Integer groupId = groupOfPerson.get(person);
if (groupId != null) {
return groupId;
}
int gid = groups.size();
Set<Integer> group = new TreeSet<>();
group.add(person);
groupOfPerson.put(person, gid);
groups.add(group);
groupHasDislikes.add(false);
return gid;
}
public static void joinGroups(int gi1, int gi2) {
Set<Integer> g1 = groups.get(gi1);
Set<Integer> g2 = groups.get(gi2);
g1.addAll(g2);
for (int p : g2) {
groupOfPerson.put(p, gi1);
}
g2.clear();
}
public static void main(String[] args) throws Exception {
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
int n = Integer.valueOf(br.readLine());
for (int i = 1; i <= n; i++) {
groupOfPerson.put(i, getOrCreateGroupId(i));
}
int k = Integer.valueOf(br.readLine());
for (int i = 0; i < k; i++) {
String[] s = br.readLine().split(" ");
int i1 = Integer.valueOf(s[0]), i2 = Integer.valueOf(s[1]);
int gi1 = getOrCreateGroupId(i1);
if (groups.get(gi1).contains(i2)) {
continue;
}
int gi2 = getOrCreateGroupId(i2);
if (groups.get(gi2).contains(i1)) {
continue;
}
joinGroups(gi1, gi2);
}
int m = Integer.valueOf(br.readLine());
for (int i = 0; i < m; i++) {
String[] s = br.readLine().split(" ");
int i1 = Integer.valueOf(s[0]), i2 = Integer.valueOf(s[1]);
int gi1 = getOrCreateGroupId(i1);
if (!groupHasDislikes.get(gi1) && !groups.get(gi1).contains(i2)) {
continue;
}
groupHasDislikes.set(gi1, true);
}
int size = 0;
for (int i = 0; i < groups.size(); i++) {
if (groupHasDislikes.get(i)) {
continue;
}
int gs = groups.get(i).size();
if (gs > size) {
size = gs;
}
}
System.out.println(size);
}
}
| Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | ea7e611cc2901d7b20cecf51059da91a | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class cf177c {
public static void main(String[] args) {
FastIO in = new FastIO(), out = in;
int n = in.nextInt();
DisjointSet ds = new DisjointSet(n);
int m = in.nextInt();
for(int i=0; i<m; i++) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;
ds.union(a, b);
}
int[] size = new int[n];
for(int i=0; i<n; i++)
size[ds.find(i)]++;
boolean[] bad = new boolean[n];
int k = in.nextInt();
for(int i=0; i<k; i++) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;
if(ds.find(a) == ds.find(b))
bad[ds.find(a)] = true;
}
int ans = 0;
for(int i=0; i<n; i++)
if(!bad[i])
ans = Math.max(ans,size[i]);
out.println(ans);
out.close();
}
static class DisjointSet {
int[] p, r;
public DisjointSet(int s) {
p = new int[s];
r = new int[s];
for(int i=0; i<s; i++)
p[i] = i;
}
public void union(int x, int y) {
int a = find(x);
int b = find(y);
if(a==b) return;
if(r[a] == r[b])
r[p[b]=a]++;
else
p[a]=p[b]=r[a]<r[b]?b:a;
}
public int find(int x) {
return p[x]=p[x]==x?x:find(p[x]);
}
}
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 | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | 28bd88b3225065098c885dfc5a372d60 | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Solution {
//<editor-fold desc="input parse" defaultstate="collapsed">
private static StringTokenizer st;
private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private static long nextLong() {
return Long.parseLong(st.nextToken());
}
private static int nextInt() {
return Integer.parseInt(st.nextToken());
}
private static double nextDouble() {
return Double.parseDouble(st.nextToken());
}
private static short nextShort() {
return Short.parseShort(st.nextToken());
}
private static byte nextByte() {
return Byte.parseByte(st.nextToken());
}
private static void initTokenizer() throws Exception {
st = new StringTokenizer(reader.readLine());
}
//</editor-fold>
private static ArrayList<Integer>[] graph;
private static boolean[] used;
private static int[] traversal;
private static int trav_index;
private static ArrayList<Integer> component;
private static void dfs(int v) {
used[v] = true;
for (int child : graph[v]) {
if (!used[child]) {
dfs(child);
}
}
traversal[trav_index++] = v;
}
private static void tdfs(int v) {
used[v] = true;
component.add(v);
for (int child : graph[v]) {
if (!used[child]) {
tdfs(child);
}
}
}
public static void main(String[] args) throws Exception {
initTokenizer();
int nodes = nextInt();
initTokenizer();
int edges = nextInt();
graph = new ArrayList[nodes];
for (int i = 0; i < graph.length; i++) {
graph[i] = new ArrayList<>();
}
for (int edge = 0; edge < edges; edge++) {
initTokenizer();
int from = nextInt() - 1;
int to = nextInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
used = new boolean [nodes];
traversal = new int [nodes];
trav_index = 0;
for (int i = 0; i < used.length; i++) {
if (!used[i]) {
dfs(i);
}
}
Arrays.fill(used, false);
int[] comp = new int[nodes];
ArrayList<Integer> csize = new ArrayList<>();
component = new ArrayList<>();
int count = 0;
for (trav_index = traversal.length - 1; trav_index >= 0; trav_index--) {
if (!used[traversal[trav_index]]) {
tdfs(traversal[trav_index]);
for (int node : component) {
comp[node] = count;
}
csize.add(component.size());
component.clear();
count++;
}
}
initTokenizer();
edges = nextInt();
boolean[] comps = new boolean[count];
for (int i = 0; i < edges; i++) {
initTokenizer();
int a = nextInt() - 1;
int b = nextInt() - 1;
if (comp[a] == comp[b]) {
comps[comp[a]] = true;
}
}
int best = 0;
for (int c = 0; c < count; c++) {
if (!comps[c]) {
best = Math.max(best, csize.get(c));
}
}
System.out.println(best);
}
} | Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | 40367d331b522a32a45a4a0cedc9b641 | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | import java.util.LinkedList;
import java.util.Scanner;
/**
* Created with IntelliJ IDEA.
* Author : Dylan
* Date : 2013-08-10
* Time : 14:40
* Project : Party 3
*/
public class Main {
static LinkedList<Integer>[] graph;
static int[] root;
static boolean[] visited;
static int n, current, max;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
graph = new LinkedList[n + 1];
visited = new boolean[n + 1];
root = new int[n + 1];
for (int i = 1; i <= n; i++) {
graph[i] = new LinkedList<Integer>();
root[i] = i;
}
int k = in.nextInt();
while (k-- > 0) {
int x = in.nextInt();
int y = in.nextInt();
graph[x].add(y);
graph[y].add(x);
int rootX = findRoot(x);
int rootY = findRoot(y);
if (rootX != rootY) {
root[rootX] = rootY;
}
}
k = in.nextInt();
while (k-- > 0) {
int rootX = findRoot(in.nextInt());
int rootY = findRoot(in.nextInt());
if (rootX == rootY) {
visited[rootX] = true;
}
}
max = 0;
for (int i = 1; i <= n; i++) {
if (visited[findRoot(i)]) continue;
current = 0;
dfs(i);
max = Math.max(max, current);
}
System.out.println(max);
}
static void dfs(int x) {
visited[x] = true;
current++;
for (int i : graph[x]) {
if (visited[i]) continue;
dfs(i);
}
}
static int findRoot(int x) {
return x == root[x] ? x : (root[x] = findRoot(root[x]));
}
}
| Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | 03e2b7ca6379425e50842e83909e41ac | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | import java.util.LinkedList;
import java.util.Scanner;
/**
* Created with IntelliJ IDEA.
* Author : Dylan
* Date : 2013-08-10
* Time : 14:40
* Project : Party 3
*/
public class Main {
static LinkedList<Integer>[] graph;
static int[] root;
static boolean[] visited;
static int n, current, max;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
graph = new LinkedList[n + 1];
visited = new boolean[n + 1];
root = new int[n + 1];
for (int i = 1; i <= n; i++) {
graph[i] = new LinkedList<Integer>();
root[i] = i;
}
int k = in.nextInt();
while (k-- > 0) {
int x = in.nextInt();
int y = in.nextInt();
graph[x].add(y);
graph[y].add(x);
int rootX = findRoot(x);
int rootY = findRoot(y);
if (rootX != rootY) {
root[rootX] = rootY;
}
}
k = in.nextInt();
while (k-- > 0) {
int rootX = findRoot(in.nextInt());
int rootY = findRoot(in.nextInt());
if (rootX == rootY) {
visited[rootX] = true;
}
}
max = 0;
for (int i = 1; i <= n; i++) {
if (visited[findRoot(i)]) continue;
current = 0;
dfs(i);
max = Math.max(max, current);
}
System.out.println(max);
}
static void dfs(int x) {
boolean res = true;
visited[x] = true;
current++;
for (int i : graph[x]) {
if (visited[i]) continue;
dfs(i);
}
}
static int findRoot(int x) {
return x == root[x] ? x : (root[x] = findRoot(root[x]));
}
}
| Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | 1b1f5d7c1267a160f5e9df5519bdb54f | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main implements Runnable {
int N, F, E;
ArrayList<Integer>[] graph;
boolean[][] enemy;
boolean[] was;
List<Integer> q;
public void solve() throws IOException {
N = nextInt();
graph = new ArrayList[N];
for(int i = 0; i < N; i++) graph[i] = new ArrayList<>();
enemy = new boolean[N][N];
was = new boolean[N];
F = nextInt();
for(int i = 0; i < F; i++){
int from = nextInt() - 1;
int to = nextInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
E = nextInt();
for(int i = 0; i < E; i++){
int from = nextInt() - 1;
int to = nextInt() - 1;
enemy[from][to] = enemy[to][from] = true;
}
int answer = 0;
for(int i = 0; i < N; i++){
if(!was[i]){
q = new LinkedList<>();
dfs(i);
if(ok()){
answer = Math.max(answer, q.size());
}
}
}
System.out.println(answer);
}
private void dfs(int x){
was[x] = true;
q.add(x);
for(int i = 0; i < graph[x].size(); i++){
if(!was[graph[x].get(i)]){
dfs(graph[x].get(i));
}
}
}
private boolean ok(){
int sz = q.size();
for(int i = 0; i < sz; i++){
for(int j = i + 1; j < sz; j++){
if(enemy[q.get(i)][q.get(j)]) return false;
}
}
return true;
}
//-----------------------------------------------------------
public static void main(String[] args) {
new Main().run();
}
public void print1Int(int[] a){
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
public void print2Int(int[][] a){
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[0].length; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
tok = null;
solve();
in.close();
} catch (IOException e) {
System.exit(0);
}
}
public String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
BufferedReader in;
StringTokenizer tok;
} | Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | a79090a3070f46f9166e8d9da9a6ffae | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
public class AbbyCupC1Party {
public static void main(String args[] ) throws Exception {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = in.nextInt();
DisjointSet ds = new DisjointSet(n);
int k = in.nextInt();
for(int i=0;i<k;i++)
ds.merge(in.nextInt()-1, in.nextInt()-1);
int m = in.nextInt();
for(int i=0;i<m;i++)
ds.destroy(in.nextInt()-1,in.nextInt()-1);
int ans = 0;
for(int i=0;i<n;i++){
int root = ds.find(i);
if(ds.canTake[root])
ans = Math.max(ans, ds.size[root]);
}
w.println(ans);
w.close();
}
static public class DisjointSet {
public int rank[],parent[],size[];
public int n;
public boolean canTake[];
public DisjointSet(int n){
this.n = n;
makeSet();
}
public void makeSet(){
rank = new int[n];
parent = new int[n];
size = new int[n];
canTake = new boolean[n];
for(int i=0;i<n;i++){
parent[i] = i;
size[i] = 1;
canTake[i] = true;
}
}
public int find(int x){
if(parent[x] != x)
parent[x] = find(parent[x]);
return parent[x];
}
public void merge(int x,int y){
int xRoot = find(x);
int yRoot = find(y);
if(xRoot == yRoot)
return;
if(rank[xRoot] < rank[yRoot]){
parent[xRoot] = yRoot;
size[yRoot] += size[xRoot];
}
else{
parent[yRoot] = xRoot;
if(rank[xRoot] == rank[yRoot]){
parent[yRoot] = xRoot;
rank[xRoot]++;
}
size[xRoot] += size[yRoot];
}
}
public void destroy(int x,int y){
int xRoot = find(x);
int yRoot = find(y);
if(xRoot == yRoot)
canTake[xRoot] = false;
}
}
static public class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
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 = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | 6ec53af988e80ff1470c22c6a827a93d | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | import java.io.*;
import java.util.*;
public class Task {
public static void main(String[] args) throws Exception {
new Task().solve();
}
int n;
boolean f[][];
boolean h[][];
boolean d[];
ArrayList <Integer> list= new ArrayList <Integer> ();
void dfs(int v)
{
d[v] = true;
// System.out.println(v);
list.add(v);
for (int i = 0; i < n; i++) {
if(!d[i] && f[i][v])
dfs(i);
}
}
void solve() throws Exception {
Reader in = new Reader();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(System.out)));
n = in.nextInt();
f = new boolean[n][n];
h = new boolean[n][n];
d = new boolean[n];
int k = in.nextInt();
for (int i = 0; i < k; i++) {
int x = in.nextInt()-1;
int y = in.nextInt()-1;
f[x][y] = true;
f[y][x] = true;
}
int l = in.nextInt();
for (int i = 0; i < l; i++) {
int x = in.nextInt()-1;
int y = in.nextInt()-1;
h[x][y] = true;
h[y][x] = true;
}
int res = 0;
for (int i = 0; i < n; i++) {
list.clear();
// System.out.println("!");
if(!d[i])
dfs(i);
boolean tr = true;
for (int j = 0; j < list.size(); j++) {
for (int j2 = 0; j2 < list.size(); j2++) {
if(j != j2)
tr = tr && (f[list.get(j)][list.get(j2)] || !(h[list.get(j)][list.get(j2)]) );
}
}
if (tr)
res = Math.max(res, list.size());
}
System.out.println(res);
// BufferedWriter out = new BufferedWriter( new
// OutputStreamWriter(System.out) );
out.flush();
out.close();
}
class Reader {
BufferedReader br;
StringTokenizer token;
Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String Next() throws Exception {
while (token == null || !token.hasMoreElements()) {
token = new StringTokenizer(br.readLine());
}
return token.nextToken();
}
int nextInt() throws Exception, Exception {
return Integer.valueOf(Next());
}
long nextLong() throws Exception, Exception {
return Long.valueOf(Next());
}
String nextString() throws Exception {
return br.readLine();
}
}
}
| Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | 92b66d42123aba942e803a838afc8dc2 | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
//4/22/12 1:43 AM
//by Abrackadabra
public class C1 {
public static void main(String[] args) throws IOException {
if (args.length > 0 && args[0].equals("Abra")) debugMode = true;
new C1().run();
/*new Thread(null, new Runnable() {
public void run() {
try {
new C1().run();
} catch (IOException e) {
e.printStackTrace();
}
}
}, "1", 1 << 24).start();*/
}
int IOMode = 0; //0 - consoleIO, 1 - <taskName>.in/out, 2 - input.txt/output.txt, 3 - test case generator
String taskName = "";
void solve() throws IOException {
int n = nextInt();
HashMap<Integer, HashSet<Integer>> friends = new HashMap<Integer, HashSet<Integer>>();
HashMap<Integer, HashSet<Integer>> enemies = new HashMap<Integer, HashSet<Integer>>();
HashSet<Integer> badColors = new HashSet<Integer>();
int[] coloring = new int[n];
int[] colorCount = new int[n + 100];
int currentColor = 1;
int m = nextInt();
for (int i = 0; i < m; i++) {
int a = nextInt() - 1, b = nextInt() - 1;
if (!friends.containsKey(a))
friends.put(a, new HashSet<Integer>());
if (!friends.containsKey(b))
friends.put(b, new HashSet<Integer>());
friends.get(a).add(b);
friends.get(b).add(a);
}
m = nextInt();
for (int i = 0; i < m; i++) {
int a = nextInt() - 1, b = nextInt() - 1;
if (!enemies.containsKey(a))
enemies.put(a, new HashSet<Integer>());
if (!enemies.containsKey(b))
enemies.put(b, new HashSet<Integer>());
enemies.get(a).add(b);
enemies.get(b).add(a);
}
for (int i = 0; i < n; i++) {
if (coloring[i] == 0) {
int toColor = currentColor++;
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(i);
coloring[i] = toColor;
colorCount[toColor]++;
while (!queue.isEmpty()) {
int q = queue.poll();
if (friends.containsKey(q))
for (int t : friends.get(q)) {
if (coloring[t] == 0) {
coloring[t] = toColor;
colorCount[toColor]++;
queue.add(t);
}
}
if (enemies.containsKey(q))
for (int t : enemies.get(q)) {
if (coloring[t] == toColor) {
badColors.add(toColor);
}
}
}
}
}
int res = 0;
for (int i = 1; i < currentColor; i++) {
if (!badColors.contains(i) && colorCount[i] > res)
res = colorCount[i];
}
out.println(res);
}
long startTime = System.nanoTime(), tempTime = startTime, finishTime = startTime;
long startMem = Runtime.getRuntime().totalMemory(), finishMem = startMem;
void run() throws IOException {
init();
if (debugMode) {
con.println("Start");
con.println("Console:");
}
solve();
finishTime = System.nanoTime();
finishMem = Runtime.getRuntime().totalMemory();
out.flush();
if (debugMode) {
int maxSymbols = 1000;
BufferedReader tbr = new BufferedReader(new FileReader("input.txt"));
char[] a = new char[maxSymbols];
tbr.read(a);
if (a[0] != 0) {
con.println("File input:");
con.println(a);
if (a[maxSymbols - 1] != 0) con.println("...");
}
tbr = new BufferedReader(new FileReader("output.txt"));
a = new char[maxSymbols];
tbr.read(a);
if (a[0] != 0) {
con.println("File output:");
con.println(a);
if (a[maxSymbols - 1] != 0) con.println("...");
}
con.println("Execution time: " + (finishTime - startTime) / 1000000000.0 + " sec");
con.println("Used memory: " + (finishMem - startMem) + " bytes");
con.println("Total memory: " + Runtime.getRuntime().totalMemory() + " bytes");
}
}
boolean tick(double x) {
if (System.nanoTime() - tempTime > x * 1e9) {
tempTime = System.nanoTime();
con.println("Tick at " + (tempTime - startTime) / 1000000000 + " sec");
con.print(" ");
return true;
}
return false;
}
static boolean debugMode = false;
PrintStream con = System.out;
void init() throws IOException {
if (debugMode && IOMode != 3) {
br = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
} else
switch (IOMode) {
case 0:
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
break;
case 1:
br = new BufferedReader(new FileReader(taskName + ".in"));
out = new PrintWriter(new FileWriter(taskName + ".out"));
break;
case 2:
br = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
break;
case 3:
out = new PrintWriter(new FileWriter("input.txt"));
break;
}
}
BufferedReader br;
PrintWriter out;
StringTokenizer in;
boolean hasMoreTokens() throws IOException {
while (in == null || !in.hasMoreTokens()) {
String line = br.readLine();
if (line == null) return false;
in = new StringTokenizer(line);
}
return true;
}
String nextString() throws IOException {
return hasMoreTokens() ? in.nextToken() : null;
}
int nextInt() throws IOException {
return Integer.parseInt(nextString());
}
long nextLong() throws IOException {
return Long.parseLong(nextString());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextString());
}
} | Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | 557775ee39de77fd24f4f1053624a5a3 | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.AbstractList;
import java.io.Writer;
import java.util.Collection;
import java.util.List;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Nguyen Trung Hieu - [email protected]
*/
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);
TaskC1 solver = new TaskC1();
solver.solve(1, in, out);
out.close();
}
}
class TaskC1 {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int count = in.readInt();
int friendshipsCount = in.readInt();
IndependentSetSystem setSystem = new RecursiveIndependentSetSystem(count);
for (int i = 0; i < friendshipsCount; i++) {
int first = in.readInt() - 1;
int second = in.readInt() - 1;
setSystem.join(first, second);
}
int[] result = new int[count];
for (int i = 0; i < count; i++)
result[setSystem.get(i)]++;
int enemiesCount = in.readInt();
for (int i = 0; i < enemiesCount; i++) {
int first = in.readInt() - 1;
int second = in.readInt() - 1;
if (setSystem.get(first) == setSystem.get(second))
result[setSystem.get(first)] = 0;
}
out.printLine(CollectionUtils.maxElement(Array.wrap(result)));
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
interface IndependentSetSystem {
public boolean join(int first, int second);
int get(int index);
public static interface Listener {
public void joined(int joinedRoot, int root);
}
}
class RecursiveIndependentSetSystem implements IndependentSetSystem {
private final int[] color;
private int setCount;
private Listener listener;
public RecursiveIndependentSetSystem(int size) {
color = new int[size];
for (int i = 0; i < size; i++)
color[i] = i;
setCount = size;
}
public RecursiveIndependentSetSystem(RecursiveIndependentSetSystem other) {
color = other.color.clone();
setCount = other.setCount;
}
public boolean join(int first, int second) {
first = get(first);
second = get(second);
if (first == second)
return false;
setCount--;
color[second] = first;
if (listener != null)
listener.joined(second, first);
return true;
}
public int get(int index) {
if (color[index] == index)
return index;
return color[index] = get(color[index]);
}
}
class CollectionUtils {
public static<T extends Comparable<T>> T maxElement(Iterable<T> collection) {
T result = null;
for (T element : collection) {
if (result == null || result.compareTo(element) < 0)
result = element;
}
return result;
}
}
abstract class Array<T> extends AbstractList<T> {
public static List<Integer> wrap(int...array) {
return new IntArray(array);
}
protected static class IntArray extends Array<Integer> {
protected final int[] array;
protected IntArray(int[] array) {
this.array = array;
}
public int size() {
return array.length;
}
public Integer get(int index) {
return array[index];
}
public Integer set(int index, Integer value) {
int result = array[index];
array[index] = value;
return result;
}
}
}
| Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | a7ffc39c24015fe48ebd14de37971df4 | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | import java.util.Scanner;
/**
* @Author Mikhail Linkov
* Date: 21.04.12
*/
public class ProblemC {
private static int [][] matrix;
private static int [] comp;
private static int count = 0;
private static int compNum;
private static int flag;
private static void dfs(int vertex) {
count++;
comp[vertex] = compNum;
for (int i = 0; i < comp.length; i++) {
if (matrix[vertex][i] == 1) {
if (comp[i] == -1) {
dfs(i);
}
}
if (matrix[vertex][i] == 2) {
if (comp[i] == comp[vertex]) {
flag = 1;
}
}
}
}
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
int vertexCount = scanner.nextInt();
int friendPairsCount = scanner.nextInt();
matrix = new int[vertexCount][vertexCount];
comp = new int[vertexCount];
compNum = 0;
for (int i = 0; i < vertexCount; i++) {
comp[i] = -1;
}
for (int i = 0; i < friendPairsCount; i++) {
int a = scanner.nextInt() - 1;
int b = scanner.nextInt() - 1;
matrix[a][b] = 1;
matrix[b][a] = 1;
}
int unFriendPairsCount = scanner.nextInt();
for (int i = 0; i < unFriendPairsCount; i++) {
int a = scanner.nextInt() - 1;
int b = scanner.nextInt() - 1;
matrix[a][b] = 2;
matrix[b][a] = 2;
}
int answer = 0;
for (int i = 0; i < vertexCount; i++) {
if (comp[i] == -1) {
compNum++;
flag = 0;
count = 0;
dfs(i);
if (flag == 0) {
if (answer < count) {
answer = count;
}
}
}
}
System.out.println(answer);
}
}
| Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | dd7b0b0ec773cd0fdcef332924af9ab0 | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CodeI
{
static class Scanner
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String nextLine()
{
try
{
return br.readLine();
}
catch(Exception e)
{
throw(new RuntimeException());
}
}
public String next()
{
while(!st.hasMoreTokens())
{
String l = nextLine();
if(l == null)
return null;
st = new StringTokenizer(l);
}
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 int[] nextIntArray(int n)
{
int[] res = new int[n];
for(int i = 0; i < res.length; i++)
res[i] = nextInt();
return res;
}
public long[] nextLongArray(int n)
{
long[] res = new long[n];
for(int i = 0; i < res.length; i++)
res[i] = nextLong();
return res;
}
public double[] nextDoubleArray(int n)
{
double[] res = new double[n];
for(int i = 0; i < res.length; i++)
res[i] = nextDouble();
return res;
}
public void sortIntArray(int[] array)
{
Integer[] vals = new Integer[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortLongArray(long[] array)
{
Long[] vals = new Long[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public void sortDoubleArray(double[] array)
{
Double[] vals = new Double[array.length];
for(int i = 0; i < array.length; i++)
vals[i] = array[i];
Arrays.sort(vals);
for(int i = 0; i < array.length; i++)
array[i] = vals[i];
}
public String[] nextStringArray(int n)
{
String[] vals = new String[n];
for(int i = 0; i < n; i++)
vals[i] = next();
return vals;
}
public Integer nextInteger()
{
String s = next();
if(s == null)
return null;
return Integer.parseInt(s);
}
public int[][] nextIntMatrix(int n, int m)
{
int[][] ans = new int[n][];
for(int i = 0; i < n; i++)
ans[i] = nextIntArray(m);
return ans;
}
public char[][] nextGrid(int r, int c)
{
char[][] grid = new char[r][];
for(int i = 0; i < r; i++)
grid[i] = next().toCharArray();
return grid;
}
public static <T> T fill(T arreglo, int val)
{
if(arreglo instanceof Object[])
{
Object[] a = (Object[]) arreglo;
for(Object x : a)
fill(x, val);
}
else if(arreglo instanceof int[])
Arrays.fill((int[]) arreglo, val);
else if(arreglo instanceof double[])
Arrays.fill((double[]) arreglo, val);
else if(arreglo instanceof long[])
Arrays.fill((long[]) arreglo, val);
return arreglo;
}
<T> T[] nextObjectArray(Class <T> clazz, int size)
{
@SuppressWarnings("unchecked")
T[] result = (T[]) java.lang.reflect.Array.newInstance(clazz, size);
for(int c = 0; c < 3; c++)
{
Constructor <T> constructor;
try
{
if(c == 0)
constructor = clazz.getDeclaredConstructor(Scanner.class, Integer.TYPE);
else if(c == 1)
constructor = clazz.getDeclaredConstructor(Scanner.class);
else
constructor = clazz.getDeclaredConstructor();
}
catch(Exception e)
{
continue;
}
try
{
for(int i = 0; i < result.length; i++)
{
if(c == 0)
result[i] = constructor.newInstance(this, i);
else if(c == 1)
result[i] = constructor.newInstance(this);
else
result[i] = constructor.newInstance();
}
}
catch(Exception e)
{
throw new RuntimeException(e);
}
return result;
}
throw new RuntimeException("Constructor not found");
}
public void printLine(int... vals)
{
if(vals.length == 0)
System.out.println();
else
{
System.out.print(vals[0]);
for(int i = 1; i < vals.length; i++)
System.out.print(" ".concat(String.valueOf(vals[i])));
System.out.println();
}
}
public void printLine(long... vals)
{
if(vals.length == 0)
System.out.println();
else
{
System.out.print(vals[0]);
for(int i = 1; i < vals.length; i++)
System.out.print(" ".concat(String.valueOf(vals[i])));
System.out.println();
}
}
public void printLine(double... vals)
{
if(vals.length == 0)
System.out.println();
else
{
System.out.print(vals[0]);
for(int i = 1; i < vals.length; i++)
System.out.print(" ".concat(String.valueOf(vals[i])));
System.out.println();
}
}
public void printLine(int prec, double... vals)
{
if(vals.length == 0)
System.out.println();
else
{
System.out.printf("%." + prec + "f", vals[0]);
for(int i = 1; i < vals.length; i++)
System.out.printf(" %." + prec + "f", vals[i]);
System.out.println();
}
}
}
static class Person
{
int id;
boolean visited = false;
ArrayList <Person> friends = new ArrayList <Person> ();
ArrayList <Person> foes = new ArrayList <Person> ();
public Person(Scanner sc, int i)
{
id = i;
}
}
static ArrayList <Person> inComponent = new ArrayList <Person> ();
static boolean[] inComponentB;
private static void floodFill(Person person)
{
if(person.visited) return;
inComponent.add(person);
person.visited = true;
for(Person f : person.friends)
floodFill(f);
}
public static void main(String[] args)
{
Scanner sc = new Scanner();
int n = sc.nextInt();
Person[] allPersons = sc.nextObjectArray(Person.class, n);
inComponentB = new boolean[n];
int k = sc.nextInt();
for(int i = 0; i < k; i++)
{
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
allPersons[u].friends.add(allPersons[v]);
allPersons[v].friends.add(allPersons[u]);
}
int m = sc.nextInt();
for(int i = 0; i < m; i++)
{
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
allPersons[u].foes.add(allPersons[v]);
allPersons[v].foes.add(allPersons[u]);
}
int best = 0;
for(int i = 0; i < n; i++)
{
if(!allPersons[i].visited)
{
inComponent.clear();
floodFill(allPersons[i]);
for(Person p : inComponent)
inComponentB[p.id] = true;
boolean viable = true;
for(Person p : inComponent)
for(Person p1 : p.foes)
if(inComponentB[p1.id])
viable = false;
for(Person p : inComponent)
inComponentB[p.id] = false;
if(viable)
best = Math.max(best, inComponent.size());
}
}
sc.printLine(best);
}
} | Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | 83025466e715a4642766636ec47081b3 | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | import java.io.*;
import java.security.SecureRandom;
import java.util.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
int n, k, m;
ArrayList<ArrayList<Integer>> friend = new ArrayList<>();
ArrayList<ArrayList<Integer>> enemy = new ArrayList<>();
boolean used[];
boolean dfs(int s) {
used[s] = true;
for (int i : friend.get(s)) {
if (!used[i]) {
dfs(i);
for (int j : enemy.get(i)) {
if (used[j]) {
return false;
}
}
}
}
return true;
}
public void solve() throws Exception {
n = sc.nextInt();
k = sc.nextInt();
for (int i = 0;i < n; ++ i) {
friend.add(new ArrayList<Integer>());
enemy.add(new ArrayList<Integer>());
}
for (int i = 0;i < k; ++ i) {
int s = sc.nextInt() - 1;
int t = sc.nextInt() - 1;
friend.get(s).add(t);
friend.get(t).add(s);
}
m = sc.nextInt();
for (int i = 0;i < m; ++ i) {
int s = sc.nextInt() - 1;
int t = sc.nextInt() - 1;
enemy.get(s).add(t);
enemy.get(t).add(s);
}
int ans = 0;
used = new boolean[n];
for (int i = 0;i < n; ++ i) {
Arrays.fill(used, false);
if (dfs(i)) {
int col = 0;
boolean can = true;
for (int ii = 0;ii < n; ++ ii) {
if (used[ii]) {
++ col;
for (int j : enemy.get(ii)) {
if (used[j]) {
can = false;
}
}
}
}
if (can)
ans = max(ans, col);
}
}
out.println(ans);
}
/*--------------------------------------------------------------*/
static String filename = "";
static boolean fromFile = false;
BufferedReader in;
PrintWriter out;
FastScanner sc;
public static void main(String[] args) {
new Thread(null, new Solution(), "", 1 << 25).start();
}
public void run() {
try {
init();
solve();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
out.close();
}
}
void init() throws Exception {
if (fromFile) {
in = new BufferedReader(new FileReader(filename+".in"));
out = new PrintWriter(new FileWriter(filename+".out"));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
sc = new FastScanner(in);
}
}
class FastScanner {
BufferedReader reader;
StringTokenizer strTok;
public FastScanner(BufferedReader reader) {
this.reader = reader;
}
public String nextToken() throws IOException {
while (strTok == null || !strTok.hasMoreTokens()) {
strTok = new StringTokenizer(reader.readLine());
}
return strTok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public BigInteger nextBigInteger() throws IOException {
return new BigInteger(nextToken());
}
public BigDecimal nextBigDecimal() throws IOException {
return new BigDecimal(nextToken());
}
} | Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | 7cbf741ec9b58adec3f45a08fccbc1bf | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static BufferedReader in;
public static PrintWriter out;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
boolean showLineError = true;
if (showLineError) {
solve();
out.close();
} else {
try {
solve();
} catch (Exception e) {
} finally {
out.close();
}
}
}
static void debug(Object... os) {
out.println(Arrays.deepToString(os));
}
private static int comp;
private static void solve() throws IOException {
int n = Integer.parseInt(in.readLine());
int m1 = Integer.parseInt(in.readLine());
List<Integer>[] g = (List<Integer>[]) new List[n];
for(int i =0;i<n;i++)
g[i]= new ArrayList<Integer>();
for(int i =0;i<m1;i++){
String[] line = in.readLine().split(" ");
int u = Integer.parseInt(line[0])-1;
int v = Integer.parseInt(line[1])-1;
g[u].add(v);
g[v].add(u);
}
int[] ok =new int[n];
Arrays.fill(ok, -1);
List<Integer> size=new ArrayList<Integer>();
for(int i =0;i<n;i++)
if(ok[i]==-1){
ok[i]=comp;
size.add(dfs(g,ok,i));
comp++;
}
int m2 = Integer.parseInt(in.readLine());
for(int i =0;i<m2;i++){
String[] line = in.readLine().split(" ");
int u = Integer.parseInt(line[0])-1;
int v = Integer.parseInt(line[1])-1;
if(ok[u]==ok[v])
size.set(ok[u], 0);
}
int ret= 0;
for(int a : size)
ret = Math.max(ret, a);
out.println(ret);
}
private static int dfs(List<Integer>[] g, int[] ok, int u) {
int ret=1;
for(int v : g[u]){
if(ok[v]==-1){
ok[v]=comp;
ret+=dfs(g,ok,v);
}
}
return ret;
}
} | Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | d8153caa1a7d0c74345d4c1633a53478 | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
public class C {
static InputStreamReader in = new InputStreamReader(System.in);
static BufferedReader bf = new BufferedReader(in);
static StreamTokenizer st = new StreamTokenizer(bf);
static int n, k, m, cnt;
static int [][] endes;
static boolean []used,t;
static boolean f;
static Set<Integer> []s;
public static void main(String[] args) throws IOException {
n = nextInt();
k = nextInt();
endes = new int[n + 1][n+1];
used = new boolean [n+1];
for (int i = 1; i <= k; i++) {
int v = nextInt();
int u = nextInt();
endes[v][u] = endes[u][v] = 1;
}
m = nextInt();
for (int i = 0; i < m; i++) {
int u = nextInt();
int v = nextInt();
endes[v][u] = endes[u][v] = 2;
}
int ans = 0;
t = new boolean [n+1];
for (int i = 1; i <=n; i++) {
if (!used[i]){
Arrays.fill(t, false);
Queue<Integer> queue = new LinkedList<Integer>();
t[i] = true;
queue.add(i);
boolean f = true;
used[i] = true;
int cnt = 0;
while (!queue.isEmpty()){
int v = queue.poll();
for (int j = 1; j <=n; j++) {
if (endes[v][j] == 1){
if (!used[j]){
used[j] = t[j] = true;
queue.add(j);
cnt++;
}
}else{
if (endes[v][j] == 2){
if (t[j]){
f = false;
}
}
}
}
}
if (f){
ans = Math.max(ans, cnt+1);
}
}
}
System.out.println(ans);
}
private static int nextInt() throws IOException {
st.nextToken();
return (int) st.nval;
}
}
| Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | dfb43c731f69b41af8b85cc285301910 | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | /*
ID: govind.3, GhpS, govindpatel
LANG: JAVA
TASK: Main
*/
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
/**
* Min segment Tree takes the minimum number at the root
*/
class MinSegmentTree {
/**
* root: Tree root, balance: input array, rl,rr:
* rl=0,rr=inputArray.length-1 minTree:segment Tree
*/
private void initMinTree(int root, int rl, int rr, int[] balance, int[] minTree) {
if (rl == rr) {
minTree[root] = balance[rl];
return;
}
int rm = (rl + rr) / 2;
initMinTree(root * 2 + 1, rl, rm, balance, minTree);
initMinTree(root * 2 + 2, rm + 1, rr, balance, minTree);
minTree[root] = Math.min(minTree[root * 2 + 1], minTree[root * 2 + 2]);
}
/**
* minTree:segment tree root:0 rl:0,rr:inputarray.length-1
* l=queryleft-1(If 1 based index),r = queryright(1-based)
*/
private int getMin(int[] minTree, int root, int rl, int rr, int l, int r) {
//l = query left-1, r = query right
if (l > r) {
return Integer.MAX_VALUE;
}
if (l == rl && r == rr) {
return minTree[root];
}
int rm = (rl + rr) / 2;
return Math.min(getMin(minTree, root * 2 + 1, rl, rm, l, Math.min(r, rm)),
getMin(minTree, root * 2 + 2, rm + 1, rr, Math.max(rm + 1, l), r));
}
}
//dsu next operation
int[] next;
private int next(int i) {
if (next[i] == i) {
return i;
}
return next[i] = next(next[i]);
}
//segment tree...
private void set(int[] t, int ind, int val) {
ind += (t.length / 2);
t[ind] = val;
int curr = 0;
while (ind > 1) {
ind >>= 1;
if (curr == 0) {
t[ind] = t[ind * 2] | t[ind * 2 + 1];
} else {
t[ind] = t[ind * 2] ^ t[2 * ind + 1];
}
curr ^= 1;
}
}
//Binary Index tree
class FenwickTree {
int[] ft;
int N;
FenwickTree(int n) {
this.N = n;
ft = new int[N];
}
private int lowbit(int x) {
return x & (-x);
}
void update(int pos, int val) {
while (pos < N) {
ft[pos] += val;
pos |= pos + 1;//0-index
}
}
int sum(int pos) {
int sum = 0;
while (pos >= 0) {
sum += ft[pos];
pos = (pos & (pos + 1)) - 1;
}
return sum;
}
int rangeSum(int left, int right) {
return sum(right) - sum(left - 1);
}
}
/**
* BINARY SEARCH IN FENWICK TREE: l=1, r=N(length), at=sumRequired,
* letter=TreeIndex(if there are many ft), ft=arrays of FT
*/
private int binarySearch(int l, int r, int at, int letter, FenwickTree[] ft) {
while (r - l > 0) {
int mid = (l + r) / 2;
int sum = ft[letter].sum(mid);
if (sum < at) {
l = mid + 1;
} else {
r = mid;
}
}
return l;
}
private int[] compress(int[] a) {
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
Arrays.sort(b);
int m = 0;
for (int i = 0; i < b.length;) {
int j = i;
while (j < b.length && b[j] == b[i]) {
j++;
}
b[m++] = b[i];
i = j;
}
for (int i = 0; i < a.length; i++) {
a[i] = Arrays.binarySearch(b, 0, m, a[i]);
}
return a;
}
class Dijkstra {
class Edge implements Comparable<Edge> {
int to;
long weight;
Edge(int t, long w) {
to = t;
weight = w;
}
public int compareTo(Edge other) {
return (int) Math.signum(weight - other.weight);
}
}
public static final long INF = (long) 1e17;
private ArrayList<Edge> adj[];
private int nodes;
private long[] dist;
private int[] prev;
private boolean[] visited;
public Dijkstra(int n) {
nodes = n;
adj = new ArrayList[nodes];
dist = new long[nodes];
prev = new int[nodes];
visited = new boolean[nodes];
for (int i = 0; i < nodes; i++) {
adj[i] = new ArrayList<Edge>();
dist[i] = INF;
prev[i] = -1;
}
}
public void add(int u, int v, long cost) {
adj[u].add(new Edge(v, cost));
}
public void dist() {
//src vertex = 0;
dist[0] = 0;
Queue<Edge> q = new PriorityQueue<Edge>();
q.add(new Edge(0, 0));
while (!q.isEmpty()) {
Edge e = q.poll();
int ind = e.to;
if (visited[ind]) {
continue;
}
visited[ind] = true;
for (Edge edge : adj[ind]) {
long newDistance = e.weight + edge.weight;
if (newDistance < dist[edge.to]) {
dist[edge.to] = newDistance;
prev[edge.to] = ind;
q.add(new Edge(edge.to, dist[edge.to]));
}
}
}
}
public ArrayList<Integer> getPrevList(int last) {
ArrayList<Integer> al = new ArrayList<Integer>();
while (last != -1) {
al.add(last);
last = prev[last];
}
return al;
}
public int[] getPrev() {
return prev;
}
public long[] getDistance() {
return dist;
}
public boolean[] getVisited() {
return visited;
}
}
class Edge {
int id, to, cap;
boolean rev;
Edge(int to, int id, int cap, boolean rev) {
this.to = to;
this.id = id;
this.cap = cap;
this.rev = rev;
}
}
int[] p;
private void solve() throws IOException {
int N = nextInt();
int M = nextInt();
p = new int[2005];
for (int i = 0; i < N; i++) {
p[i] = i;
}
for (int i = 0; i < M; i++) {
int f1 = nextInt() - 1;
int f2 = nextInt() - 1;
merge(f1, f2);
}
boolean[] good = new boolean[N];
int[] size = new int[N];
for (int i = 0; i < N; i++) {
size[get(i)]++;
good[i] = true;
}
int E = nextInt();
for (int i = 0; i < E; i++) {
int e1 = nextInt() - 1;
int e2 = nextInt() - 1;
int pe1 = get(e1);
int pe2 = get(e2);
if (pe1 == pe2) {
good[pe1] = false;
}
}
int ans = 0;
for (int i = 0; i < N; i++) {
if (good[i]) {
ans = Math.max(ans, size[i]);
}
}
out.println(ans);
}
void merge(int a, int b) {
a = get(a);
b = get(b);
if (a != b) {
p[a] = b;
}
}
int get(int a) {
// if (p[a] == a) {
// return a;
// }
while (p[a] != a) {
p[a] = p[p[a]];
a = p[a];
}
// return p[a] = get(p[a]);
return a;
}
boolean isSorted(ArrayList<Integer> al) {
int size = al.size();
for (int i = 1; i < size - 2; i++) {
if (al.get(i) > al.get(i + 1)) {
return false;
}
}
return true;
}
/**
* SHUFFLE: shuffle the array 'a' of size 'N'
*/
private void shuffle(int[] a, int N) {
for (int i = 0; i < N; i++) {
int r = i + (int) ((N - i) * Math.random());
int t = a[i];
a[i] = a[r];
a[r] = t;
}
}
/**
* TEMPLATE-STUFF: main method, run method - ( fileIO and stdIO ) and
* various methods for input like nextInt, nextLong, nextToken and
* nextDouble with some declarations.
*/
/**
* For solution to the problem ... see the solve method
*/
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
in = new BufferedReader(new FileReader("D-large.in"));
out = new PrintWriter(new BufferedWriter(new FileWriter("Main.out")));
tok = null;
solve();
in.close();
out.close();
System.exit(0);
} catch (IOException e) {//(FileNotFoundException e) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
tok = null;
solve();
in.close();
out.close();
System.exit(0);
} catch (IOException ex) {
System.out.println(ex.getMessage());
System.exit(0);
}
}
}
private String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
BufferedReader in;
StringTokenizer tok;
PrintWriter out;
}
| Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | c854d1d4951845f0c134c625cfe2e9ac | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes |
import java.util.*;
import java.io.*;
public class Main implements Runnable {
boolean[] visited;
public void solve() throws IOException {
int n = nextInt();
int m = nextInt();
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = i;
}
for (int i = 0; i < m; i++) {
int a = nextInt() - 1;
int b = nextInt() - 1;
merge(p, a, b);
}
boolean[] good = new boolean[n];
int[] size = new int[n];
for (int i = 0; i < n; i++) {
size[get(p, i)]++;
good[i] = true;
}
m = nextInt();
for (int i = 0; i < m; i++) {
int a = nextInt() - 1;
int b = nextInt() - 1;
if (get(p, a) == get(p, b)) {
good[get(p, a)] = false;
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
if (good[i]) {
ans = Math.max(ans, size[i]);
}
}
System.out.println(ans);
}
void dfs(boolean[][] board, int ind) {
visited[ind] = true;
for (int i = 0; i < board.length; i++) {
if (board[ind][i] && !visited[i]) {
dfs(board, i);
}
}
}
int answer(int[] a, int[] b) {
int n = a.length;
b = b.clone();
a = a.clone();
for (int i = 0; i < n; i++) {
if (b[i] >= 0) {
merge(a, i, b[i]);
}
}
int cnt = 0;
for (int i = 0; i < n; i++) {
if (a[i] < 0) {
cnt++;
}
}
return cnt;
}
void merge(int[] arr, int a, int b) {
a = get(arr, a);
b = get(arr, b);
if (a != b) {
arr[a] = b;
}
}
int get(int[] arr, int a) {
if (arr[a] == a) {
return a;
}
return arr[a] = get(arr, arr[a]);
}
void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N / 2; i++) {
int j = (int) (Math.random() * N);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
void print(int[] a) {
System.out.println();
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
void print(int[][] arr) {
System.out.println();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
void print(boolean[][] arr) {
System.out.println();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
boolean nextPermutation(int[] arr) {
int f = -1;
for (int i = arr.length - 2; i >= 0; i--) {
if (arr[i + 1] > arr[i]) {
f = i;
break;
}
}
if (f == -1) {
return false;
}
int s = -1;
for (int i = arr.length - 1; i >= 0; i--) {
if (arr[i] > arr[f]) {
s = i;
break;
}
}
int d = arr[f];
arr[f] = arr[s];
arr[s] = d;
f++;
int l = arr.length - 1;
while (f < l) {
d = arr[f];
arr[f] = arr[l];
arr[l] = d;
f++;
l--;
}
return true;
}
//-----------------------------------------------------------
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
tok = null;
solve();
in.close();
} catch (IOException e) {
System.exit(0);
}
}
public String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
BufferedReader in;
StringTokenizer tok;
}
| Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | cde2cf8025a6fe7d8662e489f32c225f | train_000.jsonl | 1335016800 | To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings.More formally, for each invited person the following conditions should be fulfilled: all his friends should also be invited to the party; the party shouldn't have any people he dislikes; all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people a1 and ap are connected through a chain of common friends if there exists a sequence of people a2,βa3,β...,βapβ-β1 such that all pairs of people ai and aiβ+β1 (1ββ€βiβ<βp) are friends. Help the Beaver find the maximum number of acquaintances he can invite. | 256 megabytes | /*
ID: govind.3, GhpS, govindpatel
LANG: JAVA
TASK: Main
*/
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
/**
* Min segment Tree takes the minimum number at the root
*/
class MinSegmentTree {
/**
* root: Tree root, balance: input array, rl,rr:
* rl=0,rr=inputArray.length-1 minTree:segment Tree
*/
private void initMinTree(int root, int rl, int rr, int[] balance, int[] minTree) {
if (rl == rr) {
minTree[root] = balance[rl];
return;
}
int rm = (rl + rr) / 2;
initMinTree(root * 2 + 1, rl, rm, balance, minTree);
initMinTree(root * 2 + 2, rm + 1, rr, balance, minTree);
minTree[root] = Math.min(minTree[root * 2 + 1], minTree[root * 2 + 2]);
}
/**
* minTree:segment tree root:0 rl:0,rr:inputarray.length-1
* l=queryleft-1(If 1 based index),r = queryright(1-based)
*/
private int getMin(int[] minTree, int root, int rl, int rr, int l, int r) {
//l = query left-1, r = query right
if (l > r) {
return Integer.MAX_VALUE;
}
if (l == rl && r == rr) {
return minTree[root];
}
int rm = (rl + rr) / 2;
return Math.min(getMin(minTree, root * 2 + 1, rl, rm, l, Math.min(r, rm)),
getMin(minTree, root * 2 + 2, rm + 1, rr, Math.max(rm + 1, l), r));
}
}
//dsu next operation
int[] next;
private int next(int i) {
if (next[i] == i) {
return i;
}
return next[i] = next(next[i]);
}
//segment tree...
private void set(int[] t, int ind, int val) {
ind += (t.length / 2);
t[ind] = val;
int curr = 0;
while (ind > 1) {
ind >>= 1;
if (curr == 0) {
t[ind] = t[ind * 2] | t[ind * 2 + 1];
} else {
t[ind] = t[ind * 2] ^ t[2 * ind + 1];
}
curr ^= 1;
}
}
//Binary Index tree
class FenwickTree {
int[] ft;
int N;
FenwickTree(int n) {
this.N = n;
ft = new int[N];
}
private int lowbit(int x) {
return x & (-x);
}
void update(int pos, int val) {
while (pos < N) {
ft[pos] += val;
pos |= pos + 1;//0-index
}
}
int sum(int pos) {
int sum = 0;
while (pos >= 0) {
sum += ft[pos];
pos = (pos & (pos + 1)) - 1;
}
return sum;
}
int rangeSum(int left, int right) {
return sum(right) - sum(left - 1);
}
}
/**
* BINARY SEARCH IN FENWICK TREE: l=1, r=N(length), at=sumRequired,
* letter=TreeIndex(if there are many ft), ft=arrays of FT
*/
private int binarySearch(int l, int r, int at, int letter, FenwickTree[] ft) {
while (r - l > 0) {
int mid = (l + r) / 2;
int sum = ft[letter].sum(mid);
if (sum < at) {
l = mid + 1;
} else {
r = mid;
}
}
return l;
}
private int[] compress(int[] a) {
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
Arrays.sort(b);
int m = 0;
for (int i = 0; i < b.length;) {
int j = i;
while (j < b.length && b[j] == b[i]) {
j++;
}
b[m++] = b[i];
i = j;
}
for (int i = 0; i < a.length; i++) {
a[i] = Arrays.binarySearch(b, 0, m, a[i]);
}
return a;
}
class Dijkstra {
class Edge implements Comparable<Edge> {
int to;
long weight;
Edge(int t, long w) {
to = t;
weight = w;
}
public int compareTo(Edge other) {
return (int) Math.signum(weight - other.weight);
}
}
public static final long INF = (long) 1e17;
private ArrayList<Edge> adj[];
private int nodes;
private long[] dist;
private int[] prev;
private boolean[] visited;
public Dijkstra(int n) {
nodes = n;
adj = new ArrayList[nodes];
dist = new long[nodes];
prev = new int[nodes];
visited = new boolean[nodes];
for (int i = 0; i < nodes; i++) {
adj[i] = new ArrayList<Edge>();
dist[i] = INF;
prev[i] = -1;
}
}
public void add(int u, int v, long cost) {
adj[u].add(new Edge(v, cost));
}
public void dist() {
//src vertex = 0;
dist[0] = 0;
Queue<Edge> q = new PriorityQueue<Edge>();
q.add(new Edge(0, 0));
while (!q.isEmpty()) {
Edge e = q.poll();
int ind = e.to;
if (visited[ind]) {
continue;
}
visited[ind] = true;
for (Edge edge : adj[ind]) {
long newDistance = e.weight + edge.weight;
if (newDistance < dist[edge.to]) {
dist[edge.to] = newDistance;
prev[edge.to] = ind;
q.add(new Edge(edge.to, dist[edge.to]));
}
}
}
}
public ArrayList<Integer> getPrevList(int last) {
ArrayList<Integer> al = new ArrayList<Integer>();
while (last != -1) {
al.add(last);
last = prev[last];
}
return al;
}
public int[] getPrev() {
return prev;
}
public long[] getDistance() {
return dist;
}
public boolean[] getVisited() {
return visited;
}
}
class Edge {
int id, to, cap;
boolean rev;
Edge(int to, int id, int cap, boolean rev) {
this.to = to;
this.id = id;
this.cap = cap;
this.rev = rev;
}
}
int[] p;
private void solve() throws IOException {
int N = nextInt();
int M = nextInt();
p = new int[2005];
for (int i = 0; i < N; i++) {
p[i] = i;
}
for (int i = 0; i < M; i++) {
int f1 = nextInt() - 1;
int f2 = nextInt() - 1;
merge(f1, f2);
}
boolean[] good = new boolean[N];
int[] size = new int[N];
for (int i = 0; i < N; i++) {
size[get(i)]++;
good[i] = true;
}
int E = nextInt();
for (int i = 0; i < E; i++) {
int e1 = nextInt() - 1;
int e2 = nextInt() - 1;
int pe1 = get(e1);
int pe2 = get(e2);
if (pe1 == pe2) {
good[pe1] = false;
}
}
int ans = 0;
for (int i = 0; i < N; i++) {
if (good[i]) {
ans = Math.max(ans, size[i]);
}
}
out.println(ans);
}
void merge(int a, int b) {
a = get(a);
b = get(b);
if (a != b) {
p[a] = b;
}
}
int get(int a) {
if (p[a] == a) {
return a;
}
// while (p[a] != a) {
// p[a] = p[p[a]];
// a = p[a];
// }
return p[a] = get(p[a]);
}
boolean isSorted(ArrayList<Integer> al) {
int size = al.size();
for (int i = 1; i < size - 2; i++) {
if (al.get(i) > al.get(i + 1)) {
return false;
}
}
return true;
}
/**
* SHUFFLE: shuffle the array 'a' of size 'N'
*/
private void shuffle(int[] a, int N) {
for (int i = 0; i < N; i++) {
int r = i + (int) ((N - i) * Math.random());
int t = a[i];
a[i] = a[r];
a[r] = t;
}
}
/**
* TEMPLATE-STUFF: main method, run method - ( fileIO and stdIO ) and
* various methods for input like nextInt, nextLong, nextToken and
* nextDouble with some declarations.
*/
/**
* For solution to the problem ... see the solve method
*/
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
in = new BufferedReader(new FileReader("D-large.in"));
out = new PrintWriter(new BufferedWriter(new FileWriter("Main.out")));
tok = null;
solve();
in.close();
out.close();
System.exit(0);
} catch (IOException e) {//(FileNotFoundException e) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
tok = null;
solve();
in.close();
out.close();
System.exit(0);
} catch (IOException ex) {
System.out.println(ex.getMessage());
System.exit(0);
}
}
}
private String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
BufferedReader in;
StringTokenizer tok;
PrintWriter out;
}
| Java | ["9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9"] | 2 seconds | ["3"] | NoteLet's have a look at the example. Two groups of people can be invited: {1,β2,β3} and {4,β5}, thus the answer will be the size of the largest of these groups. Group {6,β7,β8,β9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1,β2,β3,β4,β5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected). | Java 7 | standard input | [
"dsu",
"dfs and similar",
"brute force",
"graphs"
] | e1ebaf64b129edb8089f9e2f89a0e1e1 | The first line of input contains an integer n β the number of the Beaver's acquaintances. The second line contains an integer k β the number of pairs of friends. Next k lines contain space-separated pairs of integers ui,βvi β indices of people who form the i-th pair of friends. The next line contains an integer m β the number of pairs of people who dislike each other. Next m lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: 2ββ€βnββ€β14 The input limitations for getting 100 points are: 2ββ€βnββ€β2000 | 1,500 | Output a single number β the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0. | standard output | |
PASSED | ad7eeffa7fa2c60f378872b8e77d9914 | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes | import java.util.Scanner;
public class C25 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[][] dist = new int[n][n];
long sum = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[i][j] = in.nextInt();
sum += dist[i][j];
}
}
sum = sum / 2;
int k = in.nextInt();
for (int i = 0; i < k; i++) {
int from = in.nextInt() - 1;
int to = in.nextInt() - 1;
int cost = in.nextInt();
System.out.println();
if (cost >= dist[from][to]) {
System.out.println(sum);
continue;
}
for (int x = 0; x < n; x++) {
for (int y = 0; y < n; y++) {
if (dist[x][y] > dist[x][from] + dist[to][y] + cost) {
sum -= (dist[x][y]);
dist[x][y] = dist[x][from] + dist[to][y] + cost;
dist[y][x] = dist[x][from] + dist[to][y] + cost;
sum += (dist[x][y]);
} else if (dist[x][y] > dist[y][from] + dist[to][x] + cost) {
sum -= (dist[x][y]);
dist[x][y] = dist[y][from] + dist[to][x] + cost;
dist[y][x] = dist[y][from] + dist[to][x] + cost;
sum += (dist[x][y]);
}
}
}
System.out.println(sum);
}
}
}
| Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | e58afba1973a9e640e0e24ae3152817d | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] arg) {
FastScanner scan = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = scan.nextInt();
long roads[][] = new long[n+1][n+1];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
roads[i][j] = scan.nextInt();
}
}
int k = scan.nextInt();
long before = -1;
for(int i = 0; i < k; i++){
int a = scan.nextInt() - 1;
int b = scan.nextInt() - 1;
long c = scan.nextInt();
if(roads[a][b] > c)
roads[a][b] = roads[b][a] = c;
else if(before != -1){
out.print(before +" ");
continue;
}
long ret = 0;
for(int u = 0; u < n; u++){
for(int v = 0; v < n; v++){
roads[u][v] = Math.min(roads[u][v], roads[u][a] + roads[a][b] +roads[b][v]);
roads[u][v] = Math.min(roads[u][v], roads[u][b] +roads[b][a] +roads[a][v]);
}
}
for(int u = 0; u < n; u++)
for(int v = u +1; v < n; v++)
ret += roads[u][v];
before = ret;
out.print(ret + " ");
}
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream is) {
try {
br = new BufferedReader(new InputStreamReader(is));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
return null;
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.valueOf(next());
}
}
} | Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | bedfbf3d60dff6659ad68a5d83949f7a | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes | import java.util.*;
public class RoadsInBerland {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
long [][] graph= new long[n][n];
for(int i=0 ; i<n ; i++){
for(int j=0 ; j<n ; j++){
graph[i][j]=sc.nextLong();
}
}
int q=sc.nextInt();
long [] arr=new long[q];
int num=0;
long lastc=0;
for(int i=0 ; i<n ; i++){
for(int j=i ; j<n ; j++){
lastc+=graph[i][j];
}
}
for(int v=0 ; v<q ; v++){
int to=sc.nextInt()-1;
int from=sc.nextInt()-1;
int weight=sc.nextInt();
long lastw=graph[to][from];
long collect=0;
if(lastw>=weight){
graph[from][to]=weight;
graph[to][from]=weight;
for(int i=0 ;i<n ; i++){
for(int j=0 ; j<n ; j++){
long w1=Math.min(graph[i][j], graph[i][to]+graph[from][j]+weight);
long w2=Math.min(graph[i][j], graph[i][from]+graph[to][j]+weight);
graph[i][j]=Math.min(Math.min(w1 , w2) , graph[i][j]);
}
}
}
if(lastw>weight){
for(int i=0 ; i<n ; i++){
for(int j=i ; j<n ; j++){
collect+=graph[i][j];
}
}
arr[num]=collect;
lastc=collect;
}
else{
arr[num]=lastc;
}
num++;
}
System.out.printf("%d", arr[0]);
for(int i=1 ; i<q ; i++){
System.out.printf(" %d", arr[i]);
}
}
}
| Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | 86c3cfde8daac75077f0ce38fd7d403d | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes | import java.io.*;
import java.util.*;
public class RoadsinBerlandDiv2 {
private static int V;
private static int newE;
private static long[][] graph = new long[301][301] ;
public static void main(String[] args){
PrintWriter pw = new PrintWriter(System.out, true);
Scanner sc = new Scanner(System.in);
int a , b ;
long c , result;
V = sc.nextInt();
for(int i=0;i<V;i++){
for(int j=0;j<V;j++){
graph[i][j] = sc.nextLong();
}
}
newE = sc.nextInt();
for(int i=0;i<newE;i++){
a = sc.nextInt()-1;
b = sc.nextInt()-1;
c = sc.nextLong();
for(int j=0;j<V;j++){
for(int k=0;k<V;k++){
graph[j][k] = Math.min(graph[j][k], Math.min(graph[j][a]+c+graph[b][k], graph[j][b]+c+graph[a][k]));
}
}
result = 0;
for(int j=0;j<V;j++){
for(int k=j+1;k<V;k++){
result +=graph[j][k];
}
}
if(i!=newE-1){
pw.print(result+" ");
}else{
pw.print(result+"\n");
}
}
pw.close();
}
}
| Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | 8b0e05c562f3e64528036cb70d9ded9c | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class RoadsInBerland_25 {
public static void main(String[] args) throws IOException {
// ----------------------------------------------------
start();
// ----------------------------------------------------
int n = nextInt();
int[][] s = new int[n][n];
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s.length; j++) {
s[i][j] = nextInt();
}
}
int m = nextInt();
long sum = 0;
for (int i = 0; i < s.length; i++) {
for (int j = i + 1; j < s.length; j++) {
sum += s[i][j];
}
}
for (int t = 0; t < m; t++) {
int z = nextInt();
int x = nextInt();
int c = nextInt();
z--;
x--;
// if (c < s[z][x]) {
sum = 0;
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s.length; j++) {
s[i][j] = Math.min(s[i][j], Math.min(s[i][z] + c
+ s[x][j], s[i][x] + c + s[z][j]));
sum += s[i][j];
}
}
// }
if (t != m - 1) {
out.print(sum / 2 + " ");
} else {
out.println(sum / 2);
}
}
// ----------------------------------------------------
end();
// ----------------------------------------------------
}
static BufferedReader br;
static PrintWriter out;
static StringTokenizer sc;
static void start() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
sc = new StringTokenizer("");
}
static void end() throws IOException {
br.close();
out.close();
}
static String nextString() throws IOException {
while (!sc.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return null;
}
sc = new StringTokenizer(s.trim());
}
return sc.nextToken();
}
static String nextLine() throws IOException {
String s = br.readLine();
if (s == null) {
return null;
}
return s;
}
static int nextInt() throws IOException {
return Integer.parseInt(nextString());
}
static long nextLong() throws IOException {
return Long.parseLong(nextString());
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextString());
}
BigInteger nextBigInteger() throws IOException {
return new BigInteger(nextString());
}
static int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
static long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
static char[] nextCharArray() throws IOException {
return nextString().toCharArray();
}
static String[] nextStringArray(int n) throws IOException {
String[] a = new String[n];
for (int i = 0; i < n; i++)
a[i] = nextString();
return a;
}
} | Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | 12eb014a3b989dcf21ce4e5f3eeb4521 | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class RoadsInBerland_25 {
public static void main(String[] args) throws IOException {
// ----------------------------------------------------
start();
// ----------------------------------------------------
int n = nextInt();
int[][] s = new int[n][n];
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s.length; j++) {
s[i][j] = nextInt();
}
}
int m = nextInt();
long sum = 0;
for (int t = 0; t < m; t++) {
int z = nextInt();
int x = nextInt();
int c = nextInt();
z--;
x--;
sum = 0;
for (int i = 0; i < s.length; i++) {
for (int j = 0; j < s.length; j++) {
s[i][j] = Math.min(s[i][j], Math.min(s[i][z] + c
+ s[x][j], s[i][x] + c + s[z][j]));
sum += s[i][j];
}
}
if (t != m - 1) {
out.print(sum / 2 + " ");
} else {
out.println(sum / 2);
}
}
// ----------------------------------------------------
end();
// ----------------------------------------------------
}
static BufferedReader br;
static PrintWriter out;
static StringTokenizer sc;
static void start() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
sc = new StringTokenizer("");
}
static void end() throws IOException {
br.close();
out.close();
}
static String nextString() throws IOException {
while (!sc.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return null;
}
sc = new StringTokenizer(s.trim());
}
return sc.nextToken();
}
static String nextLine() throws IOException {
String s = br.readLine();
if (s == null) {
return null;
}
return s;
}
static int nextInt() throws IOException {
return Integer.parseInt(nextString());
}
static long nextLong() throws IOException {
return Long.parseLong(nextString());
}
static double nextDouble() throws IOException {
return Double.parseDouble(nextString());
}
BigInteger nextBigInteger() throws IOException {
return new BigInteger(nextString());
}
static int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
static long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
static char[] nextCharArray() throws IOException {
return nextString().toCharArray();
}
static String[] nextStringArray(int n) throws IOException {
String[] a = new String[n];
for (int i = 0; i < n; i++)
a[i] = nextString();
return a;
}
} | Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | 4062739184887d80049a6136ae9d14ce | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Erasyl Abenov
*
*
*/
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
try (PrintWriter out = new PrintWriter(outputStream)) {
TaskB solver = new TaskB();
solver.solve(1, in, out);
}
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException{
int n = in.nextInt();
int a[][] = new int[n][n];
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
a[i][j] = in.nextInt();
}
}
int k = in.nextInt();
for(int t = 0; t < k; ++t){
int x = in.nextInt();
int y = in.nextInt();
x--; y--;
int dist = in.nextInt();
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
a[i][j] = Math.min(a[i][j], Math.min(a[i][y] + a[x][j], a[i][x] + a[y][j]) + dist);
}
}
long cnt = 0;
for(int i = 0; i < n; ++i){
for(int j = i + 1; j < n; ++j){
cnt += a[i][j];
}
}
out.print(cnt);
out.print(" ");
}
}
}
class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(nextLine());
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public BigInteger nextBigInteger(){
return new BigInteger(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | b202b7f193741b77eb3e6cd0d09df4e6 | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes |
import java.util.Scanner;
public class P25C {
public P25C() {
Scanner sc = new Scanner (System.in);
int n = sc.nextInt();
long sum = 0;
int [][]distances = new int [n+1][n+1];
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n;j++){
distances[i][j] = sc.nextInt();
if (j < i){
sum += distances[i][j];
}
}
}
int t = sc.nextInt();
for (int l = 0; l < t; l++){
int x = sc.nextInt();
int y = sc.nextInt();
int z = sc.nextInt();
if (distances[x][y] > z){
distances[x][y] = z;
distances[y][x] = z;
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++){
if (distances[i][j] > distances[i][x] + distances[y][j] + distances[x][y]){
distances[i][j] = distances[i][x] + distances[y][j] + distances[x][y];
distances[j][i] = distances[i][x] + distances[y][j] + distances[x][y];
}
}
}
// for (int k = 1; k <= n; k++){
// for (int i = 1; i <= n; i++){
// for (int j = 1; j <= n; j++){
// if (distances[i][j] > distances[i][k] + distances[k][j]){
// distances[i][j] = distances[i][k] + distances[k][j];
// }
// }
// }
//
// }
sum = 0;
for (int i = 1; i <= n; i++){
for (int j = 1; j < i; j++){
sum += distances[i][j];
}
}
}
System.out.print(sum + " ");
}
sc.close();
}
public static void main (String []args){
new P25C();
}
}
| Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | 4dab4e3ed1f675547157e9d63b49dfa6 | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
/**
* Created with IntelliJ IDEA.
* Author : Dylan
* Date : 2013-08-10
* Time : 12:46
* Project : Roads in Berland
*/
public class Main {
static int[][] graph;
static int n, k;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
graph = new int[n + 1][n + 1];
long ans = 0;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
graph[i][j] = in.nextInt();
if(j > i) ans += graph[i][j];
}
}
k = in.nextInt();
while(k-- > 0) {
int x = in.nextInt();
int y = in.nextInt();
int l = in.nextInt();
if(graph[x][y] > l) {
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if(graph[i][x] + l + graph[y][j] < graph[i][j]) {
ans -= graph[i][j] - (graph[i][x] + l + graph[y][j]);
graph[i][j] = graph[i][x] + l + graph[y][j];
graph[j][i] = graph[i][j];
}
}
}
/*
for(int i = 1; i <= n; i++) {
if(l + graph[y][i] < graph[x][i]) {
ans -= graph[x][i] - l - graph[y][i];
graph[x][i] = l + graph[y][i];
graph[i][x] = graph[x][i];
}
}
for(int i = 1;i <= n; i++) {
if(graph[i][x] + l < graph[i][y]) {
ans -= graph[i][y] - l - graph[i][x];
graph[i][y] = graph[i][x] + l;
graph[y][i] = graph[i][y];
}
}
*/
}
System.out.print(ans + " ");
}
}
}
| Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | be4166e8d1c6f84659250b8ec050db23 | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
/**
* Created with IntelliJ IDEA.
* Author : Dylan
* Date : 2013-08-10
* Time : 12:46
* Project : Roads in Berland
*/
public class Main {
static int[][] graph;
static int n, k;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
graph = new int[n + 1][n + 1];
long ans = 0;
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
graph[i][j] = in.nextInt();
if(j > i) ans += graph[i][j];
}
}
k = in.nextInt();
while(k-- > 0) {
int x = in.nextInt();
int y = in.nextInt();
int l = in.nextInt();
if(graph[x][y] > l) {
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if(graph[i][x] + l + graph[y][j] < graph[i][j]) {
ans -= graph[i][j] - (graph[i][x] + l + graph[y][j]);
graph[i][j] = graph[i][x] + l + graph[y][j];
graph[j][i] = graph[i][j];
}
}
}
}
System.out.print(ans + " ");
}
}
}
| Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | e9e0619929094f9d11598553249f523c | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes | import java.util.Scanner;
public class c25 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int INF = Integer.MAX_VALUE / 2;
int n = in.nextInt();
int[][] adjMat = new int[n + 1][n + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
adjMat[i][j] = in.nextInt();
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == j) {
} else if (adjMat[i][j] == 0)
adjMat[i][j] = INF;
}
}
int k1 = in.nextInt();
long sum = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (adjMat[i][j] < INF)
sum += adjMat[i][j];
}
}
//System.out.println(sum);
while (k1-- != 0) {
int f = in.nextInt();
int t = in.nextInt();
int w = in.nextInt();
sum = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
sum+=adjMat[i][j]=Math.min(adjMat[i][j], Math.min(adjMat[i][f]+w+adjMat[t][j], adjMat[i][t]+w+adjMat[f][j]));
}
}
System.out.print(sum/2);
if(k1>0)
System.out.print(" ");
}
}
}
| Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | a467214d6a6564078ae870cf4974c06e | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main implements Runnable {
public void solve() throws IOException {
int N = nextInt();
long sum = 0;
int[][] grid = new int[N][N];
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++)
{grid[i][j] = nextInt(); sum += grid[i][j]; }
int M = nextInt();
for(int k = 0; k < M; k++){
int u = nextInt() - 1;
int v = nextInt() - 1;
int c = nextInt();
if(grid[u][v] <= c){
System.out.println(sum / 2);
continue;
}
sum = 0;
grid[u][v] = c; grid[v][u] = c;
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
grid[i][j] = Math.min(grid[i][j], grid[i][u] + grid[u][v] + grid[v][j]);
grid[i][j] = Math.min(grid[i][j], grid[i][v] + grid[v][u] + grid[u][j]);
}
}
for(int i = 0; i < N; i++){
for(int j = 0; j < N; j++){
sum += grid[i][j];
}
}
System.out.println(sum/2);
}
}
//-----------------------------------------------------------
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
tok = null;
solve();
in.close();
} catch (IOException e) {
System.exit(0);
}
}
public String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
BufferedReader in;
StringTokenizer tok;
} | Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | b54041c63c0b62b88e20be76faa60586 | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class R25qCRoadsInBerland {
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter w = new PrintWriter(System.out);
StringTokenizer st1 = new StringTokenizer(br.readLine());
int n = ip(st1.nextToken());
long dist[][] = new long[n][n];
for(int i=0;i<n;i++){
StringTokenizer st = new StringTokenizer(br.readLine());
for(int j=0;j<n;j++)
dist[i][j] = ip(st.nextToken());
}
int k = ip(br.readLine());
for(int i=0;i<k;i++){
StringTokenizer st2 = new StringTokenizer(br.readLine());
int a = ip(st2.nextToken()) - 1;
int b = ip(st2.nextToken()) - 1;
int c = ip(st2.nextToken());
long sum = 0;
for(int x=0;x<n;x++){
for(int y=0;y<n;y++){
dist[x][y] = Math.min(dist[x][y], dist[x][a] + c + dist[b][y]);
dist[x][y] = Math.min(dist[x][y], dist[x][b] + c + dist[a][y]);
sum += dist[x][y];
}
}
w.print(sum/2);
w.print(" ");
}
w.close();
}
public static int ip(String s){
return Integer.parseInt(s);
}
}
| Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | f2b044de9c466af8ab52d2db694bbb61 | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes | import java.util.Scanner;
public class Roads_in_Berland {
class Road {
public int i, j, c;
public Road(int i1, int j1, int c1) {
i = i1;
j = j1;
c = c1;
}
}
public int n, k;
public long[][] dist;
public Road[] newRoads;
void read() {
Scanner read = new Scanner(System.in);
n = read.nextInt();
dist = new long[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[i][j] = read.nextInt();
}
}
k = read.nextInt();
newRoads = new Road[k];
for (int i = 0; i < k; i++) {
int i1 = read.nextInt() - 1;
int j1 = read.nextInt() - 1;
int c1 = read.nextInt();
newRoads[i] = new Road(i1, j1, c1);
}
}
public long sum() {
long res = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
res += dist[i][j];
}
}
return res;
}
public void solve() {
read();
long[] results = new long[k];
for (int r = 0; r < k; r++) {
if (newRoads[r].c <= dist[newRoads[r].i][newRoads[r].j]) {
dist[newRoads[r].i][newRoads[r].j] = dist[newRoads[r].j][newRoads[r].i] = newRoads[r].c;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (dist[i][newRoads[r].i] + newRoads[r].c
+ dist[newRoads[r].j][j] < dist[i][j]) {
dist[i][j] = dist[j][i] = dist[i][newRoads[r].i]
+ newRoads[r].c + dist[newRoads[r].j][j];
} else if (dist[i][newRoads[r].j] + newRoads[r].c
+ dist[newRoads[r].i][j] < dist[i][j]) {
dist[i][j] = dist[j][i] = dist[i][newRoads[r].j]
+ newRoads[r].c + dist[newRoads[r].i][j];
}
}
}
}
long res = sum();
results[r] = res;
}
for (int i = 0; i < k - 1; i++) {
System.out.print(results[i] + " ");
}
System.out.println(results[k - 1]);
}
public static void main(String[] args) {
new Roads_in_Berland().solve();
}
}
| Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | aaaa1c46c508887c7e438e8d9ccf439f | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Zyflair Griffane
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
PandaScanner in = new PandaScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
C solver = new C();
solver.solve(1, in, out);
out.close();
}
}
class C {
public void solve(int testNumber, PandaScanner in, PrintWriter out) {
int n = in.nextInt();
long[][] adj = new long[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
adj[i][j] = in.nextInt();
}
}
for (int z = 0; z < n; z++) {
for (int x = 0; x < n; x++) {
for (int y = 0; y < n; y++) {
adj[x][y] = Math.min(adj[x][y], adj[x][z] + adj[z][y]);
}
}
}
int k = in.nextInt();
long res[] = new long[k];
for (int i = 0; i < k; i++) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
int d = in.nextInt();
adj[u][v] = adj[v][u] = Math.min(adj[u][v], d);
for (int a = 0; a < n; a++) {
for (int b = 0; b < n; b++) {
adj[a][b] = Math.min(adj[a][b], adj[a][u] + adj[u][b]);
}
}
for (int a = 0; a < n; a++) {
for (int b = 0; b < n; b++) {
adj[a][b] = Math.min(adj[a][b], adj[a][v] + adj[v][b]);
}
}
for (int a = 0; a < n; a++) {
for (int b = a; b < n; b++) {
res[i] += adj[a][b];
}
}
}
out.println(Arrays.toString(res).replaceAll("[^ 0-9]", ""));
}
}
class PandaScanner {
public BufferedReader br;
public StringTokenizer st;
public InputStream in;
public PandaScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(this.in = in));
}
public String nextLine() {
try {
return br.readLine();
}
catch (Exception e) {
return null;
}
}
public String next() {
if (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine().trim());
return next();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | 1390aea27bb73632f61b90467b85e28d | train_000.jsonl | 1280761200 | There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length β an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them β for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road. | 256 megabytes | import java.io.*;
import java.util.*;
public class try23 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner k=new Scanner(System.in);
int n=k.nextInt();
int[][]dist0=new int[n][n];
for (int i = 0; i < dist0.length; i++) {
for (int j = 0; j < dist0.length; j++) {
dist0[i][j]=k.nextInt();
}
}
int road=k.nextInt();
for (int i = 0; i < road; i++) {
int first=k.nextInt();
int second=k.nextInt();
int cost=k.nextInt();
int[][]dist1=new int[n][n];
dist1[first-1][second-1]=cost;
dist1[second-1][first-1]=cost;
//for (int k1 = 0; k1 < dist1.length; k1++) {
for (int ii = 0; ii < dist1.length; ii++) {
for (int j = 0; j < dist1.length; j++) {
int min=Math.min(dist0[ii][second-1]+dist0[first-1][j], dist0[ii][first-1]+dist0[second-1][j]);
dist1[ii][j]=Math.min(dist0[ii][j], min+cost);
}
}
long sum=0;
boolean[][]check=new boolean[n][n];
for (int j = 0; j < dist1.length; j++) {
for (int j2 = 0; j2 < dist1.length; j2++) {
if(!check[j][j2])
sum+=dist1[j][j2];
check[j][j2]=true;
check[j2][j]=true;
dist0[j][j2]=dist1[j][j2];
}
}
//}
System.out.print(sum+" ");
}
}
}
| Java | ["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"] | 2 seconds | ["3", "17 12"] | null | Java 7 | standard input | [
"shortest paths",
"graphs"
] | 5dbf91f756fecb004c836a628eb23578 | The first line contains integer n (2ββ€βnββ€β300) β amount of cities in Berland. Then there follow n lines with n integer numbers each β the matrix of shortest distances. j-th integer in the i-th row β di,βj, the shortest distance between cities i and j. It is guaranteed that di,βiβ=β0,βdi,βjβ=βdj,βi, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1ββ€βkββ€β300) β amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1ββ€βai,βbiββ€βn,βaiββ βbi,β1ββ€βciββ€β1000) β ai and bi β pair of cities, which the road connects, ci β the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself. | 1,900 | Output k space-separated integers qi (1ββ€βiββ€βk). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs. | standard output | |
PASSED | e5344dfe8da3e8ae23b845b607452559 | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Rubanenko
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
final int MAX_VALUE = 1 << 20;
final int MD = 1000000000 + 7;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[MAX_VALUE];
int[] c = new int[MAX_VALUE];
int[] deg = new int[MAX_VALUE];
long[] f = new long[MAX_VALUE];
deg[0] = 1;
for (int i = 1; i < MAX_VALUE; i++) {
deg[i] = deg[i - 1] * 2;
if (deg[i] >= MD) deg[i] -= MD;
}
for (int i = 0; i < n; i++) {
int x = in.nextInt();
// int x = i;
a[x]++;
f[x]++;
c[x]++;
}
long[] ff = new long[MAX_VALUE];
int ans = deg[n] - 1;
if (ans < 0) ans += MD;
long[] fact = new long[23];
fact[0] = 1;
for (int i = 1; i <= 21; i++) {
fact[i] = fact[i - 1] * ((long) i);
}
for (int j = 0; j < 20; j++) {
for (int mask = MAX_VALUE - 1; mask > 0; mask--) {
if (f[mask] > 0) {
for (int i = 0; i < 20; i++) {
if (((1 << i) & mask) > 0) ff[mask ^ (1 << i)] += f[mask];
}
}
}
for (int mask = MAX_VALUE - 1; mask > 0; mask--) {
c[mask] += ff[mask] / fact[j + 1];
f[mask] = ff[mask];
ff[mask] = 0;
}
}
for (int mask = 1; mask < MAX_VALUE; mask++) {
if ((Integer.bitCount(mask) & 1) == 1) ans -= deg[c[mask]] - 1;
else ans += deg[c[mask]] - 1;
if (ans >= MD) ans -= MD;
if (ans < 0) ans += MD;
}
out.println(ans);
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String nextLine() {
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | 71d04a677873890110624ea7c1b10c94 | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class MainClass
{
public static void main(String[] args)throws IOException
{
Reader in = new Reader();
int n = in.nextInt();
int[] A = new int[n]; for (int i=0;i<n;i++) A[i] = in.nextInt();
int[] dp = new int[1 << 20]; int univMask = (1 << 20) - 1;
for (int i=0;i<n;i++) ++dp[univMask ^ A[i]];
for (int i=0;i<20;i++)
for (int mask=0;mask<(1 << 20);++ mask)
if ((mask & (1 << i)) > 0)
dp[mask] += dp[mask ^ (1 << i)];
int[] count = new int[1 << 20];
for (int mask=0;mask<(1 << 20);mask++) count[mask] += dp[mask ^ univMask];
long M = 1_000_000_007L;
long ans = 0L;
for (int mask = 0;mask < (1 << 20); ++ mask)
{
long pow = binPow(count[mask], M);
int x = Integer.bitCount(mask) % 2; if (x == 1) x = -1; else x = 1;
ans = (ans + (1L * x * pow) % M + M) % M;
}
System.out.println(ans);
}
public static long binPow(int n, long M)
{
if (n == 0) return 1;
long res = binPow(n / 2, M);
res = (res * res) % M;
if (n % 2 == 1) res = (res * 2L) % M;
return res;
}
}
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\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | 3af8386cd3e11bb1a3d6b2cbe49d4f8b | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
* @author pttrung
*/
public class D_Round_257_Div1 {
public static long MOD = 1000000007;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int[]data = new int[n];
long[]count = new long[1<<20];
for(int i = 0; i < n; i++){
data[i] = in.nextInt();
count[data[i]]++;
}
// System.out.println("HE HE");
for(int i = 0; i < 20; i++){
for(int j = (1 << 20) - 1; j >= 0; j-- ){
if(((1<<i) & j) == 0){
count[j] += count[j | (1<<i)];
}
}
}
long result = 0;
for(int i = 0; i < 1<<20; i++){
long sign = Integer.bitCount(i) % 2 == 0 ? 1 : -1;
result += (sign * pow(2, count[i]) + MOD) % MOD;
result %= MOD;
}
out.println(result);
out.close();
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return x - o.x;
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | 1a3a80fd17e6bd26da361fb5d8f9655b | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | /*Author: Satyajeet Singh, Delhi Technological University*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.math.*;
public class Main{
/*********************************************Constants******************************************/
static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static long mod=(long)1e9+7;
static long mod1=998244353;
static boolean sieve[];
static ArrayList<Integer> primes;
static long factorial[],invFactorial[];
static ArrayList<Pair> graph[];
static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
static int pptr=0;
static String st[];
/****************************************Solutions Begins***************************************/
static int n;
static long input[];
static long dp[][];
static long dfs(int mask,int bit){
if(bit==20){
//printMask(mask);
return input[mask];
}
if(dp[mask][bit]!=-1){
return dp[mask][bit];
}
long ans=0;
if((mask&(1<<bit))!=0){
ans+=dfs(mask,bit+1);
}
else{
ans+=dfs(mask,bit+1)+dfs(mask^(1<<bit),bit+1);
}
dp[mask][bit]=ans;
return dp[mask][bit];
}
static final int m=20;
public static void main(String[] args) throws Exception{
nl();
n=pi();
nl();
dp=new long[(1<<m)+1][m+1];
for(long arr[]:dp)
Arrays.fill(arr,-1);
input=new long[(1<<m)+1];
for(int i=0;i<n;i++){
input[pi()]++;
}
int cnt[]=new int[1<<m];
for(int mask=1;mask<(1<<m);mask++){
cnt[mask]=cnt[mask&(mask-1)]+1;
}
// debug(cnt);
// for(int i=0;i<=m;i++){
// for(int mask=0;mask<(1<<m);mask++){
// if((mask&(1<<i))!=0){
// dp[mask^(1<<i)]+=dp[mask];
// }
// }
// }
// debug(dp);
long ans=0;
for(int i=0;i<(1<<m);i++){
int b=cnt[i];
if(b%2==0){
ans+=modulo(2,dfs(i,0),mod)-1;
if(ans>=mod)ans-=mod;
}
else{
ans-=modulo(2,dfs(i,0),mod)-1;
if(ans<0)ans+=mod;
}
}
out.println(ans);
/****************************************Solutions Ends**************************************************/
out.flush();
out.close();
}
/****************************************Template Begins************************************************/
static void nl() throws Exception{
pptr=0;
st=br.readLine().split(" ");
}
static void nls() throws Exception{
pptr=0;
st=br.readLine().split("");
}
static int pi(){
return Integer.parseInt(st[pptr++]);
}
static long pl(){
return Long.parseLong(st[pptr++]);
}
static double pd(){
return Double.parseDouble(st[pptr++]);
}
/***************************************Precision Printing**********************************************/
static void printPrecision(double d){
DecimalFormat ft = new DecimalFormat("0.000000000000000000000");
out.print(ft.format(d));
}
/**************************************Bit Manipulation**************************************************/
static void printMask(long mask){
System.out.println(Long.toBinaryString(mask));
}
static long countBit(long mask){
long ans=0;
while(mask!=0){
if(mask%2==1){
ans++;
}
mask/=2;
}
return ans;
}
/******************************************Graph*********************************************************/
static void Makegraph(int n){
graph=new ArrayList[n];
for(int i=0;i<n;i++){
graph[i]=new ArrayList<>();
}
}
static void addEdge(int a,int b){
graph[a].add(new Pair(b,1));
}
static void addEdge(int a,int b,int c){
graph[a].add(new Pair(b,c));
}
/*********************************************PAIR********************************************************/
static class Pair implements Comparable<Pair> {
int u;
int v;
int index=-1;
public Pair(int u, int v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/******************************************Long Pair*******************************************************/
static class Pairl implements Comparable<Pairl> {
long u;
long v;
int index=-1;
public Pairl(long u, long v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pairl other = (Pairl) o;
return u == other.u && v == other.v;
}
public int compareTo(Pairl other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/*****************************************DEBUG***********************************************************/
public static void debug(Object... o) {
if(!oj)
System.out.println(Arrays.deepToString(o));
}
/************************************MODULAR EXPONENTIATION***********************************************/
static long modulo(long a,long b,long c) {
long x=1;
long y=a%c;
while(b > 0){
if(b%2 == 1){
x=(x*y)%c;
}
y = (y*y)%c; // squaring the base
b /= 2;
}
return x%c;
}
/********************************************GCD**********************************************************/
static long gcd(long x, long y)
{
if(x==0)
return y;
if(y==0)
return x;
long r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
/******************************************SIEVE**********************************************************/
static void sieveMake(int n){
sieve=new boolean[n];
Arrays.fill(sieve,true);
sieve[0]=false;
sieve[1]=false;
for(int i=2;i*i<n;i++){
if(sieve[i]){
for(int j=i*i;j<n;j+=i){
sieve[j]=false;
}
}
}
primes=new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(sieve[i]){
primes.add(i);
}
}
}
/********************************************End***********************************************************/
} | Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | d61893cccd907fe910617240f95eb404 | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | /*Author: Satyajeet Singh, Delhi Technological University*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.math.*;
public class Main{
/*********************************************Constants******************************************/
static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static long mod=(long)1e9+7;
static long mod1=998244353;
static boolean sieve[];
static ArrayList<Integer> primes;
static long factorial[],invFactorial[];
static ArrayList<Pair> graph[];
static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
static int pptr=0;
static String st[];
/****************************************Solutions Begins***************************************/
static int n,input[];
static long dp[];
static long dfs(int mask){
if(dp[mask]!=-1){
return dp[mask];
}
long ans=input[mask];
for(int i=0;i<20;i++){
if((mask&(1<<i))!=0){
ans=(ans+dfs(mask^(1<<i)));
if(ans>=mod)ans-=mod;
}
}
dp[mask]=ans;
return dp[mask];
}
static final int m=20;
public static void main(String[] args) throws Exception{
nl();
n=pi();
nl();
dp=new long[1<<m];
int mx=0;
for(int i=0;i<n;i++){
int a=pi();
mx=Math.max(a,mx);
dp[a]++;
}
int cnt[]=new int[1<<m];
for(int mask=1;mask<(1<<m);mask++){
cnt[mask]=cnt[mask&(mask-1)]+1;
}
// debug(cnt);
for(int i=0;i<=m;i++){
for(int mask=0;mask<(1<<m);mask++){
if((mask&(1<<i))!=0){
dp[mask^(1<<i)]+=dp[mask];
}
}
}
// debug(dp);
long ans=0;
for(int i=0;i<(1<<m);i++){
int b=cnt[i];
if(b%2==0){
ans+=modulo(2,dp[i],mod)-1;
if(ans>=mod)ans-=mod;
}
else{
ans-=modulo(2,dp[i],mod)-1;
if(ans<0)ans+=mod;
}
}
out.println(ans);
/****************************************Solutions Ends**************************************************/
out.flush();
out.close();
}
/****************************************Template Begins************************************************/
static void nl() throws Exception{
pptr=0;
st=br.readLine().split(" ");
}
static void nls() throws Exception{
pptr=0;
st=br.readLine().split("");
}
static int pi(){
return Integer.parseInt(st[pptr++]);
}
static long pl(){
return Long.parseLong(st[pptr++]);
}
static double pd(){
return Double.parseDouble(st[pptr++]);
}
/***************************************Precision Printing**********************************************/
static void printPrecision(double d){
DecimalFormat ft = new DecimalFormat("0.000000000000000000000");
out.print(ft.format(d));
}
/**************************************Bit Manipulation**************************************************/
static void printMask(long mask){
System.out.println(Long.toBinaryString(mask));
}
static long countBit(long mask){
long ans=0;
while(mask!=0){
if(mask%2==1){
ans++;
}
mask/=2;
}
return ans;
}
/******************************************Graph*********************************************************/
static void Makegraph(int n){
graph=new ArrayList[n];
for(int i=0;i<n;i++){
graph[i]=new ArrayList<>();
}
}
static void addEdge(int a,int b){
graph[a].add(new Pair(b,1));
}
static void addEdge(int a,int b,int c){
graph[a].add(new Pair(b,c));
}
/*********************************************PAIR********************************************************/
static class Pair implements Comparable<Pair> {
int u;
int v;
int index=-1;
public Pair(int u, int v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/******************************************Long Pair*******************************************************/
static class Pairl implements Comparable<Pairl> {
long u;
long v;
int index=-1;
public Pairl(long u, long v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pairl other = (Pairl) o;
return u == other.u && v == other.v;
}
public int compareTo(Pairl other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/*****************************************DEBUG***********************************************************/
public static void debug(Object... o) {
if(!oj)
System.out.println(Arrays.deepToString(o));
}
/************************************MODULAR EXPONENTIATION***********************************************/
static long modulo(long a,long b,long c) {
long x=1;
long y=a%c;
while(b > 0){
if(b%2 == 1){
x=(x*y)%c;
}
y = (y*y)%c; // squaring the base
b /= 2;
}
return x%c;
}
/********************************************GCD**********************************************************/
static long gcd(long x, long y)
{
if(x==0)
return y;
if(y==0)
return x;
long r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
/******************************************SIEVE**********************************************************/
static void sieveMake(int n){
sieve=new boolean[n];
Arrays.fill(sieve,true);
sieve[0]=false;
sieve[1]=false;
for(int i=2;i*i<n;i++){
if(sieve[i]){
for(int j=i*i;j<n;j+=i){
sieve[j]=false;
}
}
}
primes=new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(sieve[i]){
primes.add(i);
}
}
}
/********************************************End***********************************************************/
} | Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | 52677f8409d4318c63d908d85f8ad3bb | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
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;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
final int MOD = (int)(1e9 + 7);
int n = in.nextInt();
int k = 20;
int[] d = new int[1 << k];
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
++d[a[i]];
}
for (int i = 0; i < k; i++) {
for (int mask = 0; mask < 1<<k; mask++) {
if ((mask & (1 << i)) == 0) {
d[mask] += d[mask | (1 << i)];
}
}
}
int[] p2 = new int[n + 1];
p2[0] = 1;
for (int i = 1; i < p2.length; i++) {
p2[i] = 2 * p2[i - 1] % MOD;
}
int ans = 0;
for (int mask = 0; mask < 1<<k; mask++) {
if (Integer.bitCount(mask) % 2 == 0) {
ans += p2[d[mask]];
if (ans >= MOD) {
ans -= MOD;
}
} else {
ans -= p2[d[mask]];
if (ans < 0) {
ans += MOD;
}
}
}
out.println(ans);
}
}
class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | b38de0f145eee100e5c3d5a06155c4bb | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class D257 {
static final long MOD = (long)(1e9+7);
static long[] fs;
static long[][] memo;
public static void main(String[] args) {
MyScanner in = new MyScanner();
int n = in.nextInt();
fs = new long[1 << 20];
for(int i=0;i<n;i++) {
fs[in.nextInt()]++;
}
memo = new long[20][1 << 20];
for(long[] arr : memo)
Arrays.fill(arr, -1);
long ans = 0;
for(int i=0;i<fs.length;i++) {
int bitcount = Integer.bitCount(i);
ans += fmpow(2,countSupersets(i, 0)) * (bitcount % 2 == 0 ? 1 : -1);
ans %= MOD;
}
if(ans < 0)
ans += MOD;
System.out.println(ans);
}
static long fmpow(long a, long b) {
if(b == 0)
return 1;
if(b == 1)
return a;
long bonus = 1;
while(b > 1) {
if(b % 2 != 0)
bonus = (bonus * a) % MOD;
b /= 2;
a = (a*a)%MOD;
}
return (a*bonus)%MOD;
}
public static long countSupersets(int mask, int idx) {
if(idx == 20)
return fs[mask];
if(memo[idx][mask] != -1)
return memo[idx][mask];
long ans = countSupersets(mask, idx+1);
int bit = 1 << idx;
if((mask & bit) == 0)
ans += countSupersets(mask|bit,idx+1);
return memo[idx][mask] = ans;
}
private static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(this.next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | 656c058f7d893ecb6635495538e57b3e | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.math.BigInteger;
import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
//SOLUTION BEGIN
//Into the Hardware Mode
void pre() throws Exception{}
void solve(int TC) throws Exception{
int n = ni(), B = 20;
long[] a = new long[1<<B];
long MOD = (long)1e9+7;
for(int i = 0; i< n; i++)a[ni()]++;
for(int b = 0; b< B; b++)
for(int i = 0; i< 1<<B; i++)
if(((i>>b)&1)==1)
a[i^(1<<b)] += a[i];
long ans = 0;
for(int i = 0; i< a.length; i++)ans = (ans+MOD+(bit(i)%2 == 0?1:-1)*pow(2, a[i], MOD))%MOD;
pn(ans);
}
long pow(long a, long p, long MOD){
long o = 1;
for(;p>0;p>>=1){
if((p&1)==1)o = (o*a)%MOD;
a = (a*a)%MOD;
}
return o;
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
void exit(boolean b){if(!b)System.exit(0);}
// long IINF = (long)1e15;
final int INF = (int)1e9+2, MX = (int)2e6+5;
DecimalFormat df = new DecimalFormat("0.00000000000");
double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8;
static boolean multipleTC = false, memory = false, fileIO = false;
FastReader in;PrintWriter out;
void run() throws Exception{
long ct = System.currentTimeMillis();
if (fileIO) {
in = new FastReader("");
out = new PrintWriter("");
} else {
in = new FastReader();
out = new PrintWriter(System.out);
}
//Solution Credits: Taranpreet Singh
int T = (multipleTC) ? ni() : 1;
pre();
for (int t = 1; t <= T; t++) solve(t);
out.flush();
out.close();
System.err.println(System.currentTimeMillis() - ct);
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
else new Main().run();
}
int[][] make(int n, int[] from, int[] to, boolean f){
int[][] g = new int[n][];int[]cnt = new int[n];
for(int i:from)cnt[i]++;if(f)for(int i:to)cnt[i]++;
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]];
for(int i = 0; i< from.length; i++){
g[from[i]][--cnt[from[i]]] = to[i];
if(f)g[to[i]][--cnt[to[i]]] = from[i];
}
return g;
}
int[][][] makeS(int n, int[] from, int[] to, boolean f){
int[][][] g = new int[n][][];int[]cnt = new int[n];
for(int i:from)cnt[i]++;if(f)for(int i:to)cnt[i]++;
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][];
for(int i = 0; i< from.length; i++){
g[from[i]][--cnt[from[i]]] = new int[]{to[i], i};
if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i};
}
return g;
}
int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));}
int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str;
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
} | Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | 5b537deb50671afcaa7605b9a71b6aa3 | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.util.Scanner;
/**
* Created by David Lee on 2017/6/22.
*/
public class Main {
static int P = 1000000007, N = 1<<20 + 5, k = 1<<20;
static int a[] = new int [N];
static private int ksm(int a, int b)
{
int c = 1, d = a;
while (b > 0)
{
if((b & 1) != 0)
c = (int)((long)c * d %P);
d = (int)((long)d * d %P);
b >>= 1;
}
return c;
}
static private void FWT(int [] a, int n, int L, int R)
{
if(L==R)
return;
int i, h = n/2;
for (i = L; i < L + h; i++)
a[i] = (a[i] + a[i+h])%P;
FWT(a, h, L, L + h - 1);
FWT(a, h, L + h, R);
}
static private void IFWT(int [] a, int n, int L, int R)
{
if(L==R)
return;
int i, h = n/2;
for (i = L; i < L + h; i++)
a[i] = (a[i] - a[i+h] + P)%P;
IFWT(a, h, L, L + h - 1);
IFWT(a, h, L + h, R);
}
static public void main(String args[]) {
int T;
Scanner Cin = new Scanner(System.in);
//T = Cin.nextInt();
T = 1;
while (T > 0)
{
T--;
int n, i;
n = Cin.nextInt();
for (i = 0; i < k; i++)
a[i] = 0;
for (i = 1; i <= n; i++)
a[Cin.nextInt()]++;
FWT(a, k, 0, k - 1);
//for (i = 0; i < 10; i++)
//System.out.printf("%d ",a[i]);
//System.out.println();
for (i = 0; i < k; i++)
a[i] = ksm(2, a[i]);
IFWT(a, k, 0, k - 1);
System.out.printf("%d\n", a[0]);
}
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | ed30e843c6d29b65a986f8112904a622 | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes |
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Round257Div1D {
public static long mod = (long)1e9+7;
public static void solve() {
int n = s.nextInt();
int m = 20;
int size = 1<<m;
int[] dp = new int[size];
for(int i = 0 ;i<n;i++) {
int x = s.nextInt();
dp[x]++;
}
for(int i=0;i<m;i++) {
for(int mask = 0;mask<size;mask++) {
if((mask & (1<<i))==0) {
dp[mask]+=dp[mask|(1<<i)];
}
}
}
long ans = 0;
for(int i=0;i<size;i++) {
int bits = Integer.bitCount(i);
if((bits&1)==0) {
ans = ans + fast(2,dp[i]);
ans%=mod;
}else {
ans = ans - fast(2,dp[i]);
ans%=mod;
if(ans<0) {
ans+=mod;
}
}
}
out.println(ans);
}
public static long fast(long a,long n) {
if(n == 1) {
return a%mod;
}else if(n==0) {
return 1;
}
long ans= fast(a,n/2);
ans = ans * ans;
ans%=mod;
if((n&1)==1) {
ans = ans * a;
ans%=mod;
}
return ans;
}
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
s = new FastReader();
solve();
out.close();
}
public static FastReader s;
public static PrintWriter out;
public static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | 88b9f1d0be0c8ff1f446f894d115db12 | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
static final int LOG = 20;
static final int N = 1 << LOG;
static final int MOD = 1_000_000_007;
void solve() throws IOException {
int n = nextInt();
int[] a = new int[N];
for (int i = 0; i < n; i++) {
int x = nextInt();
a[N - 1 - x]++;
}
for (int i = 0; i < LOG; ++i)
for (int mask = 0; mask < N; mask++)
if (test(mask, i)) {
a[mask] = (a[mask] + a[mask ^ (1 << i)]) % MOD;
}
for (int i = 0, j = N - 1; i < j; i++, j--) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
int[] p2 = new int[n + 1];
p2[0] = 1;
for (int i = 0; i < n; i++) {
p2[i + 1] = (p2[i] << 1) % MOD;
}
int ans = 0;
// System.err.println(Arrays.toString(a));
for (int i = 0; i < N; i++) {
int val = p2[a[i]];
if ((Integer.bitCount(i) & 1) == 0) {
ans += val;
} else {
ans += MOD - val;
}
ans %= MOD;
}
out.println(ans);
}
static boolean test(int mask, int i) {
return ((mask >> i) & 1) == 1;
}
D() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new D();
}
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 | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | 226ccbfd8d663c9f8777b168c5096f96 | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
}
void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DJzzhuAndNumbers solver = new DJzzhuAndNumbers();
solver.solve(1, in, out);
out.close();
}
static class DJzzhuAndNumbers {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int[] ar = new int[n];
long[] dp = new long[(1 << 20) | 5];
for (int i = 0; i < n; i++)
dp[(ar[i] = in.scanInt())]++;
for (int i = 0; i < 20; i++) {
for (int j = 0; j < (1 << 20); j++) {
if (((1 << i) & j) != 0) dp[j ^ (1 << i)] += dp[j];
}
}
long mod = (1000000007);
long ans = 0;
for (int i = 0; i < (1 << 20); i++) {
if (Integer.bitCount(i) % 2 == 1) {
ans -= (CodeHash.pow(2, dp[i], mod));
if (ans < 0) ans += mod;
if (ans >= mod) ans -= mod;
} else {
ans += (CodeHash.pow(2, dp[i], mod));
if (ans < 0) ans += mod;
if (ans >= mod) ans -= mod;
}
}
out.println(ans);
}
}
static class CodeHash {
public static long pow(long a, long b, long m) {
long res = 1;
a %= m;
while (b > 0) {
if ((b & 1) == 1) res = (res * a) % m;
a = (a * a) % m;
b >>= 1;
}
return res;
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (index >= total) {
index = 0;
try {
total = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (total <= 0) return -1;
}
return buf[index++];
}
public int scanInt() {
int 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();
}
}
return neg * integer;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | a6e8c3854be5f49dae0c47691b9e2bac | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.*;
import java.lang.*;
import java.util.*;
public class JzzuandNumbers{
int n;
int[] arr;
int[][] dp;
int[] READER;
void read()throws Exception{
READER = new int[1000005];
BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
String line;
int ind=0;
while ((line = bi.readLine()) != null)
for (String numStr: line.split("\\s"))
READER[++ind] = Integer.parseInt(numStr);
}
long fe( long a,long b ){
if( b==0 ) return 1;
long t = fe(a,b/2);
t = t*t%1000000007;
if( (b&1)!=0 ) t = t*a%1000000007;
return t;
}
int countbit( int x ){
int r=0;
while( x!=0 ){
r += (x&1);
x >>= 1;
}
return r;
}
void solve()throws Exception{
dp = new int[(1<<20)+2][22];
arr =new int[1<<20];
read();
n = READER[1];
for( int i=2;i<=n+1;i++ ){
arr[i-1] = READER[i];
dp[arr[i-1]][0]++;
}
for( int i=(1<<20)-1;i>=0;i-- )
for( int k=0;k<20;k++ ){
dp[i][k+1] += dp[i][k-1+1];
if( (i&(1<<k))==0 && i+(1<<k)<=(1<<20)-1 )
dp[i][k+1] += dp[i+(1<<k)][k-1+1];
}
long res=0;
for( int i=0;i<(1<<20);i++ ){
res += (fe( -1,countbit(i) )*( fe( 2,dp[i][20] )-1 )+1000000007)%1000000007;
}
System.out.println( (res%1000000007+1000000007)%1000000007 );
}
static public void main( String args[] )throws Exception{
new JzzuandNumbers().solve();
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 8 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | 44316496060cefb8ca322d662b0cadda | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author ilyakor
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
static final int maxn = 1 << 18;
static final int mod = 1000 * 1000 * 1000 + 7;
static int[] bcnt = new int[maxn];
int[] p2;
static {
bcnt[0] = 0;
for (int i = 1; i < maxn; ++i) {
bcnt[i] = (i % 2) + bcnt[i / 2];
}
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
p2 = new int[maxn * 4];
p2[0] = 1;
for (int i = 1; i < p2.length; ++i)
p2[i] = (p2[i - 1] * 2) % mod;
int n = in.nextInt();
// int n = 1000 * 1000;
int[][] d = new int[5][maxn];
for (int i = 0; i < n; ++i) {
int x = in.nextInt();
// int x = i;
d[x % 4][x / 4] += 1;
if (x % 4 == 1 || x % 4 == 0)
d[4][x / 4] += 1;
}
int[] D = new int[maxn];
long res = 0;
for (int i = 0; i < maxn; ++i) {
if (d[3][i] == 0) continue;
addNum(D, i, d[3][i]);
}
res = calc(D);
int[] D_save = Arrays.copyOf(D, maxn);
for (int i = 0; i < maxn; ++i) {
if (d[2][i] == 0) continue;
addNum(D, i, d[2][i]);
}
res = (res - calc(D)) % mod;
res = (res + mod) % mod;
for (int i = 0; i < maxn; ++i) {
if (d[4][i] == 0) continue;
addNum(D, i, d[4][i]);
}
// for (int i = 0; i < maxn; ++i) {
// if (d[1][i] == 0) continue;
// addNum(D, i, d[1][i]);
// }
// for (int i = 0; i < maxn; ++i) {
// if (d[0][i] == 0) continue;
// addNum(D, i, d[0][i]);
// }
res = (res + calc(D)) % mod;
D = D_save;
for (int i = 0; i < maxn; ++i) {
if (d[1][i] == 0) continue;
addNum(D, i, d[1][i]);
}
res = (res - calc(D)) % mod;
res = (res + mod) % mod;
//
// for (int i = 0; i < maxn; ++i) {
// for (int j = i; ; j = (j - 1) & i) {
// D[j] += d[i];
// if (j == 0) break;
// }
// }
// for (int i = 0; i < maxn; ++i) {
// int x = i;
// long s = 1;
// while (x > 0) {
// if (x % 2 == 1) s = -s;
// x /= 2;
// }
// res = (res + s * (long) p2[D[i]]) % mod;
// }
out.printLine(res);
}
private long calc(int[] d) {
long res = 0;
for (int i = 0; i < maxn; ++i) {
if (bcnt[i] % 2 == 0) {
res += p2[d[i]];
res %= mod;
} else {
res -= p2[d[i]];
res %= mod;
res += mod;
res %= mod;
}
}
return res;
}
static void addNum(int[] D, int x, int cnt) {
for (int j = x; ; j = (j - 1) & x) {
D[j] += cnt;
if (j == 0) break;
}
}
}
class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0)
return -1;
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 6 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | 7c1a2aff3cb79a5f2ad36795cce981f3 | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes | import java.io.*;
import static java.lang.Math.pow;
import java.math.BigInteger.*;
import static java.math.BigInteger.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.fill;
//<editor-fold defaultstate="collapsed" desc="Imports">
//</editor-fold>
// https://netbeans.org/kb/73/java/editor-codereference_ru.html#display
//<editor-fold defaultstate="collapsed" desc="Main">
public class Main {
private void run() {
Locale.setDefault(Locale.US);
boolean oj = true;
try {
oj = System.getProperty("MYLOCAL") == null;
} catch (Exception e) {
}
if (oj) {
sc = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
} else {
try {
sc = new FastScanner(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
} catch (IOException e) {
MLE();
}
}
Solver s = new Solver();
s.sc = sc;
s.out = out;
s.solve();
err.println("Time: " + (System.currentTimeMillis() - timeBegin) / 1e3);
out.flush();
}
private void show(int[] arr) {
for (int v : arr) {
err.print(" " + v);
}
err.println();
}
public static void MLE() {
// int[][] arr = new int[1024 * 1024][];
// for (int i = 0; i < arr.length; i++) {
// arr[i] = new int[1024 * 1024];
// }
System.exit(0);
}
public static void main(String[] args) {
new Main().run();
}
long timeBegin = System.currentTimeMillis();
FastScanner sc;
PrintWriter out;
PrintStream err = System.err;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="FastScanner">
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStreamReader reader) {
br = new BufferedReader(reader);
st = new StringTokenizer("");
}
String next() {
while (!st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException ex) {
Main.MLE();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
//</editor-fold>
class Solver {
FastScanner sc;
PrintWriter out;
PrintStream err = System.err;
final int cntBits = 20, mod = (int)1e9 + 7;
int n;
int[] a;
int[] f = new int[1<<cntBits];
final int[] pow2 = new int[1<<cntBits];
{
pow2[0] = 1;
for (int i = 1; i < pow2.length; i++) {
pow2[i] = (pow2[i-1] + pow2[i-1]);
if( mod <= pow2[i] ) pow2[i] -= mod;
}
}
void solve(){
n = sc.nextInt();
a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
++f[a[i]];
}
// bf();
for (int k = 1; k <= cntBits; k++) {
for (int msk = 0; msk < (1<<cntBits); msk++) {
if( (msk&(1<<(k-1))) == 0 ){
f[msk] = f[msk] + f[msk+(1<<(k-1))];
if( mod <= f[msk] ) f[msk] -= mod;
}
}
}
// err.println(Arrays.toString(f[cntBits]));
long ans = 0;
for (int msk = 0; msk < (1<<cntBits); msk++) {
long cur = pow2[f[msk]];
if( Integer.bitCount(msk)%2==0 )
ans += cur;
else
ans -= cur;
}
ans = ( ans % mod + mod ) % mod;
out.println( ans );
}
// void bf() {
// int[] ffff = new int[1<<cntBits];
// for (int ai : a) {
// for (int x = 0; x < ffff.length; x++) {
// if ((ai & x) == x) {
// ++ffff[x];
// }
// }
// }
// err.println(Arrays.toString(ffff));
//
// double ans = 0;
// for (int x = 0; x < ffff.length; x++) {
// ans += pow(-1, Integer.bitCount(x)) * pow(2, ffff[x]);
// out.printf("%4s %d %3.0f\n",
// Integer.toBinaryString(x),
// ffff[x],
// pow(-1, Integer.bitCount(x)) * pow(2, ffff[x]));
// }
// out.println(ans);
// }
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 6 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | 4b89ae7daa46dee60392746cf9479f44 | train_000.jsonl | 1405774800 | Jzzhu have n non-negative integers a1,βa2,β...,βan. We will call a sequence of indexes i1,βi2,β...,βik (1ββ€βi1β<βi2β<β...β<βikββ€βn) a group of size k. Jzzhu wonders, how many groups exists such that ai1 & ai2 & ... & aikβ=β0 (1ββ€βkββ€βn)? Help him and print this number modulo 1000000007 (109β+β7). Operation x & y denotes bitwise AND operation of two numbers. | 256 megabytes |
import java.util.Scanner;
public class Main {
private static final int mod = (int)1e9+7;
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
Scanner sc = new Scanner(System.in);
String input1 = sc.nextLine();
String input2 = sc.nextLine();
int n = Integer.parseInt(input1);
String str1[] = input2.split(" ");
int xs[] = new int[n];
for(int i=0; i<str1.length; i++){
xs[i] = Integer.parseInt(str1[i].trim());
}
int[] pow2 = new int[n+1];
pow2[0] = 1;
for(int i = 1; i < pow2.length; i++) pow2[i] = (int)(pow2[i-1] * 2L % mod);
int[] dp = new int[1<<20];
for(int x : xs) {
dp[x]++;
}
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 1 << 20; j++) {
if((j>>>i&1) == 0) {
dp[j] += dp[j|1<<i];
}
}
}
long ans = 0;
for(int i = 0; i < 1 << 20; i++) {
ans += (1L-Integer.bitCount(i)%2*2) * pow2[dp[i]]%mod;
}
System.out.println((ans % mod + mod) % mod);
}
catch(Exception e){
e.printStackTrace();
}
}
}
| Java | ["3\n2 3 3", "4\n0 1 2 3", "6\n5 2 0 5 2 1"] | 2 seconds | ["0", "10", "53"] | null | Java 6 | standard input | [
"dp",
"combinatorics",
"bitmasks"
] | 0c5bc07dec8d8e0201695ad3edc05877 | The first line contains a single integer n (1ββ€βnββ€β106). The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β106). | 2,400 | Output a single integer representing the number of required groups modulo 1000000007 (109β+β7). | standard output | |
PASSED | 4d1dd17a56ca79c7f79a42843b3ac2e5 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int j = 0; j < t; j++) {
int n = sc.nextInt();
int aaa = 0;
int numOdds = 0;
int numEvens = 0;
for (int i = 0; i < n; i++) {
aaa = sc.nextInt();
if (aaa % 2 != 0) numOdds++;
else numEvens++;
}
if ((numOdds != 0 && numOdds % 2 == 0 && numEvens > 0) || numOdds % 2 != 0)
System.out.println("YES");
else
System.out.println("NO");
}
}
} | Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | 7e01e2aad5530723c3ec168fa10ef13a | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
for (int i = 0; i < n; i++) {
int odd = 0 , ev = 0 ,sum = 0 ;
int p = input.nextInt();
for (int j = 0; j <p; j++) {
int x = input.nextInt();
sum += x;
if (x%2==0) {ev++;}
else {odd++;}
}
if (sum%2!=0||odd>0&&ev>0) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
input.close();
}
} | Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | 34adc87eeb0d6a7ddfae02171b7248a1 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args)throws IOException{
Scanner sc = new Scanner (System.in);
int cont = sc.nextInt();
while(cont > 0){
int tam = sc.nextInt();
int[] arr = new int[tam];
int sum = 0;
for(int i=0;i<arr.length;i++){
arr[i] = sc.nextInt();
sum = sum + arr[i];
}
if(sum % 2 != 0) System.out.println("YES");
else subArr(arr);
cont--;
}
}
public static void subArr(int[] arr){
boolean ir = false;
int pr =0;
for(int i=0; i<arr.length;i++){
if(arr[i]% 2 != 0){
ir = true;
}else{
pr++;
}
}
if(ir == true && pr > 0){
System.out.println("YES");
}else System.out.println("NO");
}
}
| Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | add1941952bcc500db965053b872a123 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args)throws IOException{
Scanner sc = new Scanner (System.in);
int cont = sc.nextInt();
while(cont > 0){
int tam = sc.nextInt();
int[] arr = new int[tam];
int sum = 0;
boolean ir = false;
int pr =0;
for(int i=0;i<arr.length;i++){
arr[i] = sc.nextInt();
if(arr[i]% 2 != 0) ir = true;
else pr++;
sum = sum + arr[i];
}
if(sum % 2 != 0) System.out.println("YES");
else{
if(ir == true && pr > 0) System.out.println("YES");
else System.out.println("NO");
}
cont--;
}
}
}
| Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | 62fe949f2495ed054bfc73e989b7a5a6 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | /**
* @author : Kshitij
*/
import java.io.*;
import java.util.InputMismatchException;
public class Main {
public static void main(String[] xps){
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
StringBuilder stringBuilder = new StringBuilder();
int t=in.readInt();
while (t-->0){
int n=in.readInt();
int[] array=new int[n];
for (int i = 0; i <n ; i++) {
array[i]=in.readInt();
}
stringBuilder.append(solver(array)).append("\n");
}
out.println(stringBuilder);
}
public static String solver(int[] array){
int oddCounter=0;
boolean even=false;
for (int a :
array) {
if (a%2!=0)
oddCounter++;
else
even=true;
}
if ((oddCounter>0 && even)||(oddCounter%2!=0))
return "YES";
else
return "NO";
}
private static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 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;
}
public 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;
}
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);
}
}
private 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]);
}
writer.flush();
}
public void println(Object... objects) {
print(objects);
writer.println();
writer.flush();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
} | Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | 9151a086a4ea5ca80399a50eab4bd472 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int testCase = scan.nextInt();
for(int i = 0; i < testCase; i++){
int odd = 0;
int even = 0;
int num = scan.nextInt();
for(int j = 0; j < num; j++){
int input = scan.nextInt();
if(input % 2 == 0)
even++;
else
odd++;
}
if(num % 2 == 1){
if(odd > 0)
System.out.println("YES");
else
System.out.println("NO");
}
else{
if(odd > 0 && even> 0)
System.out.println("YES");
else
System.out.println("NO");
}
}
}
} | Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | 150fc78593c194982351c53a8f6f5530 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class Array_Odd_Sum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int test = in.nextInt();
for (int i = 0; i < test; i++) {
int size = in.nextInt();
int sum = 0;
int se = 0;
int oh = 0, eh = 0;
if (size % 2 == 0) {
se = 1;
}
int arr[] = new int[size];
for (int i1 = 0; i1 < size; i1++) {
arr[i1] = in.nextInt();
if (arr[i1] % 2 == 0) {
eh = 1;
} else {
oh = 1;
}
}
for (int i1 = 0; i1 < size; i1++) {
sum = sum + arr[i1];
}
if (sum % 2 != 0) {
System.out.println("YES");
continue;
}
if (se == 0) {
if (eh == 1 && oh == 1) {
System.out.println("YES");
continue;
} else {
System.out.println("NO");
}
} else {
if (eh == 1 && oh == 1) {
System.out.println("YES");
continue;
} else {
System.out.println("NO");
}
}
}
}
} | Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | bd7900fb58c5d987ef83533a4c3a7e02 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
import java.util.Arrays;
import java.lang.*;
import java.io.*;
import java.util.*;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.*;
import java.util.function.Function;
public class ArrayWithOddSum {
public static void main(String[] args)throws IOException {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i=0;i<t;i++){
int n = sc.nextInt();
int a[] = new int[n];
for(int j=0;j<n;j++){
a[j] = sc.nextInt();
}
System.out.println(check(a));
}
sc.close();
}
static String check(int[] a){
int sum =0;
for(int i=0;i<a.length;i++){
sum += a[i];
}
if( Arrays.stream(a).map(x -> x % 2).distinct().count() == 2 || sum % 2 !=0){
return "YES";
}else{
return "NO";
}
}
} | Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | afc4825d4e308900658af01ef5365a85 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes |
import java.util.Scanner;
/**
*
* @author Tonmoy
*/
public class Array_with_Odd_Sum_1296A {
public static void main(String[] args) {
Scanner In=new Scanner(System.in);
int t=In.nextInt();
for (int i = 0; i < t; i++) {
int n=In.nextInt();
int sum=0;
int num;
int even=0;
int odd=0;
for (int j = 0; j < n; j++) {
num=In.nextInt();
sum=sum+num;
if(num%2==0){
even++;
}
else{
odd++;
}
}
if(sum%2!=0){
System.out.println("YES");
}
else{
if(odd!=0 && even!=0){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
}
}
| Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | 14e362b4a975b67d1236f1848ad367e0 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
static int a =0;
static int b =0;
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner input = new Scanner(System.in);
int test= input.nextInt();
while(test-->0){
int n = input.nextInt();
int sum =0;
int count[] = new int[2];
for(int i =0;i<n;i++){
int a = input.nextInt();
sum+=a;
count[a%2]++;
}
if(sum%2 == 1){
System.out.println("YES");
}else{
if(count[1] == 0)System.out.println("NO");
else if(count[0] == 0 && count[1]%2 == 0)System.out.println("NO");
else System.out.println("YES");
}
}
}
}
| Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | 673e38d05d24b4ef670360539c85aa1b | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
static int a =0;
static int b =0;
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner input = new Scanner(System.in);
int test= input.nextInt();
while(test-->0){
int n = input.nextInt();
int sum =0;
int count[] = new int[2];
for(int i =0;i<n;i++){
int a = input.nextInt();
sum+=a;
count[a%2]++;
}
if(sum%2 == 1){
System.out.println("YES");
}else{
if(count[1]>0 && count[0]>0 && count[1]%2 == 0 && count[0]%2 == 1)System.out.println("YES");
else if(count[1]>0 && count[0]>0 && count[1]%2 == 0 && count[0]%2 == 0)System.out.println("YES");
else if(count[1]>0 && count[0]>0 && count[1]%2 == 1 && count[0]%2 == 1)System.out.println("YES");
else System.out.println("NO");
}
}
}
}
| Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | 189c29f5003b5de06dc3baff038c3bbc | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class qqq {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int testcase = scan.nextInt();
int num;
for (int i = 0; i < testcase; i++) {
num = scan.nextInt();
int n = 0;
boolean odd = false;
boolean even = false;
for (int j = 0; j < num; j++) {
n = scan.nextInt();
if (n % 2 != 0) {
odd = true;
} else {
even = true;
}
}
if (num % 2 == 0) {
if (odd == true && even == true) {
System.out.println("YES");
} else {
System.out.println("NO");
}
} else {
if (odd == true) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
scan.close();
}
} | Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | 91a433e2bca9be011b97919bebeba617 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
public class code_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);
int t=in.nextInt();
while(t--!=0){
int n=in.nextInt();
int o=0,e=0,sum=0;
for(int i=0;i<n;i++){
int x=in.nextInt();
if(x%2==0){
e+=1;
}
else
o+=1;
sum+=x;
}
if(sum%2!=0 || (e>=1 && o>=1)){
System.out.println("Yes");
}
else{
System.out.println("No");
}
}
}
} | Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | f49680106840eb4039590b2cdf355b59 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
static FastReader sc=new FastReader();
public static void main(String[] args) {
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
int a[]=readArray(n);
int c=0;
for(int e:a) {
if(e%2==1) c++;
}
if(c%2==1 || (c%2==0 && c!=n && c!=0)) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
static int[] readArray(int n) {
int a[]=new int [n];
for(int i=0;i<n;i++) {
a[i]=sc.nextInt();
}
return a;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | 310a8d39a77a16e293f24604f49f5b70 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class Code1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
for(int i=0;i<t;i++){
int n = scan.nextInt();
int[] arr = new int[n];
int sum =0;
int even =0;
int odd =0;
for(int j=0;j<n;j++){
arr[j] = scan.nextInt();
if(arr[j]%2!=0){
odd++;
}
else{
even++;
}
sum+= arr[j];
}
if(sum%2!=0 ){
System.out.println("YES");
}
else {
if (odd != 0 && even != 0) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
} | Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | 3dbf26b18e1ccf808edbdf7828fdea60 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.lang.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n=sc.nextInt();
int arr[] = new int[n];
int sum=0;
boolean even = false;
boolean odd = false;
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
sum = sum + arr[i];
if((arr[i] % 2)==0){
even = true;
}
else{
odd = true;
}
}
if((sum % 2) != 0){
System.out.println("YES");
}
else{
if(even && odd){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
}
} | Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | 5940968eb76c5180a30a33417aeff9ab | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
public class ASoln {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(st == null || !st.hasMoreElements()) {
try {
st= new StringTokenizer(br.readLine());
}catch(IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] args) {
FastReader sc = new FastReader();
int t = sc.nextInt();
while(t-- > 0) {
int n = sc.nextInt();
int a[] = new int[n];
for(int i =0; i<n; i++) {
a[i] = sc.nextInt();
}
int c = 0;
int even = 0;
for(int i = 0; i<n; i++) {
if(a[i]%2 != 0) {
c++;
}if(a[i]%2 == 0) {
even++;
}
}
if(n%2==0) {
if(even == 0) {
System.out.println("NO");
}
else if(c == 0) {
System.out.println("NO");
}else if(c != 0) {
System.out.println("YES");
}
}else {
if(c != 0) {
System.out.println("YES");
}else {
System.out.println("NO");
}
}
}
}
}
| Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | 7c54c3c366cbe44acbd4b0c991aa1427 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
//int cnt=0,cnt1=0;
while(t-->0)
{
String ans="";
int cnt[] =new int[2];
int n=sc.nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
if(a[i]%2==0)
cnt[0]++;
else
cnt[1]++;
}
if(cnt[0]==0 && cnt[1]==0)
ans="NO";
else if(cnt[0]==cnt[1])
ans="YES";
else if(cnt[1]==0)
ans="NO";
else if(cnt[0]==0)
{
if(cnt[1]%2!=0)
ans="YES";
else
ans="NO";
}
else if(cnt[0]!=0)
ans="YES";
System.out.println(ans);
}
}
} | Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | c95d1b544c6d6d6a0c9763c3a8dd1546 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class codeforces
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i = 0; i<t; i++){
int n = sc.nextInt();
int oddCount = 0;
for(int j = 0; j<n; j++){
int val = sc.nextInt();
if(val%2==1){
oddCount++;
}
}
if(n%2==0&&(oddCount==0||oddCount==n)||oddCount==0){
System.out.println("NO");
}else{
System.out.println("YES");
}
}
}
} | Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | 7576b894c3bc5d5a355b9166893f7884 | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class MyClass {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i=0;i<t;i++){
int size = sc.nextInt();
int even=0,odd=0;
for(int j=0;j<size;j++){
int d=sc.nextInt();
if(d%2 == 0)
even++;
else
odd++;
}
if(even ==size)
System.out.println("NO");
else if(odd==size && size%2==0)
System.out.println("NO");
else
System.out.println("YES");
}
}
} | Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output | |
PASSED | f48fd69b832b04e05ab8e2e4988295cd | train_000.jsonl | 1580826900 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose two indices $$$1 \le i, j \le n$$$ such that $$$i \ne j$$$ and set $$$a_i := a_j$$$. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose $$$i$$$ and $$$j$$$ and replace $$$a_i$$$ with $$$a_j$$$).Your task is to say if it is possible to obtain an array with an odd (not divisible by $$$2$$$) sum of elements.You have to answer $$$t$$$ independent test cases. | 256 megabytes | import java.util.*;
public class Main{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int j = 0; j < t; j++){
int n = in.nextInt();
int odd = 0;
int even = 0;
for(int i = 0; i < n; i++){
int a = in.nextInt();
if(a%2 == 0){
even ++;
} else {
odd ++;
}
}
if((odd%2 == 1) || (odd%2 == 0 && even > 0 && odd !=0)){
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}
| Java | ["5\n2\n2 3\n4\n2 2 8 8\n3\n3 3 3\n4\n5 5 5 5\n4\n1 1 1 1"] | 1 second | ["YES\nNO\nYES\nNO\nNO"] | null | Java 11 | standard input | [
"math"
] | 2e8f7f611ba8d417fb7d12fda22c908b | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) β the number of test cases. The next $$$2t$$$ lines describe test cases. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2000$$$) β the number of elements in $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2000$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ ($$$\sum n \le 2000$$$). | 800 | For each test case, print the answer on it β "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.