exec_outcome stringclasses 1 value | code_uid stringlengths 32 32 | file_name stringclasses 111 values | prob_desc_created_at stringlengths 10 10 | prob_desc_description stringlengths 63 3.8k | prob_desc_memory_limit stringclasses 18 values | source_code stringlengths 117 65.5k | lang_cluster stringclasses 1 value | prob_desc_sample_inputs stringlengths 2 802 | prob_desc_time_limit stringclasses 27 values | prob_desc_sample_outputs stringlengths 2 796 | prob_desc_notes stringlengths 4 3k β | lang stringclasses 5 values | prob_desc_input_from stringclasses 3 values | tags listlengths 0 11 | src_uid stringlengths 32 32 | prob_desc_input_spec stringlengths 28 2.37k β | difficulty int64 -1 3.5k β | prob_desc_output_spec stringlengths 17 1.47k β | prob_desc_output_to stringclasses 3 values | hidden_unit_tests stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | c67f7e1c535e3d9e9c423f31d7e90e19 | train_004.jsonl | 1267117200 | The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points. | 64 megabytes |
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
/**
* Created by Scruel on 2016/3/29.
*/
//http://codeforces.com/problemset/problem/2/A
public class CF2_A
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
HashMap<String, Integer> map = new HashMap<>();
int n = input.nextInt();
String[] winnerList = new String[n];
int[] scoreList = new int[n];
int count = 0;
int max = 0, realMax = 0;//0δΈΊεε§εΌοΌεδΈδΌεΊη°θ΄ζ°θε©ηζ
ε΅
String tempWinner = "";
for (int i = 0; i < n; i++)
{
String name = input.next();
int score = input.nextInt();
if (map.get(name) == null)
map.put(name, score);
else
map.replace(name, score + map.get(name));
if (realMax < map.get(name))//εΎε°η¬¬δΈδΈͺζε€§εΌηδΊΊ
{
scoreList[count] = map.get(name);
winnerList[count++] = name;
}
}
Set<String> set = map.keySet();
for (Iterator<String> iter = set.iterator(); iter.hasNext(); )
{
String key = iter.next();
if (map.get(key) > max)
max = map.get(key);
}
for (int i = 0; i < n; i++)
{
if (scoreList[i] >= max && map.get(winnerList[i]) == max)
{
System.out.println(winnerList[i]);
return;
}
}
}
} | Java | ["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"] | 1 second | ["andrew", "andrew"] | null | Java 8 | standard input | [
"implementation",
"hashing"
] | c9e9b82185481951911db3af72fd04e7 | The first line contains an integer number n (1βββ€ββnβββ€ββ1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive. | 1,500 | Print the name of the winner. | standard output | |
PASSED | b49b5eeda71f1f8681c3fcbd317a57c4 | train_004.jsonl | 1267117200 | The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points. | 64 megabytes | import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Solution {
public static int maxMap(Map<String, Integer> m) {
int max = -1;
for(Entry<String, Integer> e:m.entrySet()) {
if(e.getValue()>max)
max=e.getValue();
}
return max;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int nr = Integer.parseInt(s.nextLine());
String[] scoreList = new String[nr];
Map<String, Integer> scoreMap = new HashMap<String, Integer>();
for(int i = 0; i < nr; i++) {
scoreList[i] = s.nextLine();
scoreMap.merge(scoreList[i].substring(0,scoreList[i].indexOf(' ')),
Integer.parseInt(scoreList[i].substring(scoreList[i].indexOf(' ')+1)),
(a,b)-> a+b);
}
s.close();
int max = maxMap(scoreMap);
Map<String, Integer> otherScoreMap = new HashMap<String, Integer>();
for(int i = 0; i < nr; i++) {
otherScoreMap.merge(scoreList[i].substring(0,scoreList[i].indexOf(' ')),
Integer.parseInt(scoreList[i].substring(scoreList[i].indexOf(' ')+1)),
(a,b)-> a+b);
if(otherScoreMap.get(scoreList[i].substring(0,scoreList[i].indexOf(' ')))>=max &&
scoreMap.get(scoreList[i].substring(0,scoreList[i].indexOf(' ')))==max) {
System.out.println(scoreList[i].substring(0,scoreList[i].indexOf(' ')));
break;
}
}
}
} | Java | ["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"] | 1 second | ["andrew", "andrew"] | null | Java 8 | standard input | [
"implementation",
"hashing"
] | c9e9b82185481951911db3af72fd04e7 | The first line contains an integer number n (1βββ€ββnβββ€ββ1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive. | 1,500 | Print the name of the winner. | standard output | |
PASSED | 0eabf9d92c14f5c3b13417b8cefcd373 | train_004.jsonl | 1267117200 | The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points. | 64 megabytes | import java.util.Scanner;
public class Hudai{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int noOfRounds;
noOfRounds = scan.nextInt();
String str[][] = new String[noOfRounds][2];
String storeInput[][] = new String[noOfRounds][2];
String newStr[][] = new String[noOfRounds][2];
int x = 0;
for(int i=0, j = 0;j<noOfRounds;i++){
storeInput[j][0] = scan.next();
storeInput[j][1] = scan.next();
for(int k = 0; k <= i; k++){
if(str[k][0] != null){
if(str[k][0].equals(storeInput[j][0])){
int n = Integer.parseInt(str[k][1]) + Integer.parseInt(storeInput[j][1]);
str[k][1] = Integer.toString(n);
i = i - 1;
}
}
else
{
str[i][0] = storeInput[j][0];
str[i][1] = storeInput[j][1];
}
}
j++;
x = i;
}
String winners[][] = new String[noOfRounds][2];
int maxScore = 0;
for(int l = 0; l<= x; l++)
{
if(Integer.parseInt(str[l][1]) > maxScore){
maxScore = Integer.parseInt(str[l][1]);
}
}
for(int l = 0,i = 0; l<= x; l++)
{
if(Integer.parseInt(str[l][1]) == maxScore){
winners[i][0] = str[l][0];
winners[i][1] = str[l][1];
i++;
}
}
int winnerIndex = -1;
for(int i=0, j = 0;j<noOfRounds;i++){
for(int k = 0; k <= i; k++){
if(newStr[k][0] != null){
if(newStr[k][0].equals(storeInput[j][0])){
int n = Integer.parseInt(newStr[k][1]) + Integer.parseInt(storeInput[j][1]);
newStr[k][1] = Integer.toString(n);
if(maxScore <= Integer.parseInt(newStr[k][1]))
{
for(int p =0; winners[p][0] != null; p++){
if(newStr[k][0].equals(winners[p][0]))
{ winnerIndex = k;
break;
}
}
}
i = i - 1;
}
}
else
{
newStr[i][0] = storeInput[j][0];
newStr[i][1] = storeInput[j][1];
if( maxScore <= Integer.parseInt(newStr[i][1])){
for(int p =0; winners[p][0] != null; p++){
if(newStr[i][0].equals(winners[p][0]))
{ winnerIndex = k;
break;
}
}
}
}
}
if(winnerIndex != -1)
break;
j++;
}
System.out.println( newStr[winnerIndex][0]);
}
} | Java | ["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"] | 1 second | ["andrew", "andrew"] | null | Java 8 | standard input | [
"implementation",
"hashing"
] | c9e9b82185481951911db3af72fd04e7 | The first line contains an integer number n (1βββ€ββnβββ€ββ1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive. | 1,500 | Print the name of the winner. | standard output | |
PASSED | d82e768beb831d856d99a3ce8fe56270 | train_004.jsonl | 1267117200 | The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points. | 64 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
/**
* Created by William on 1/21/2015.
*/
public class winner2 {
static class History{
int[] MaxRound = new int[50];
int[] MaxScore = new int[50];
int CurrentRound;
int CurrentScore;
int counter = 0;
History(int Currentround, int CurrentScore)
{
this.CurrentRound = Currentround;
this.CurrentScore = CurrentScore;
this.MaxRound[0] = Currentround;
this.MaxScore[0] = CurrentScore;
}
public void Update(int round, int score)
{
CurrentRound = round;
CurrentScore += score;
if(CurrentScore > MaxScore[counter])
{
counter++;
MaxScore[counter] = CurrentScore;
MaxRound[counter] = round;
}
}
public int Max()
{
return MaxScore[counter];
}
public int MaxRound()
{
return MaxRound[counter];
}
public int roundpassedMax(int max)
{
for(int i = 0; i < counter; i++)
{
if(MaxScore[i]>=max)
return MaxRound[i];
}
return MaxRound[counter];
}
}
public static void main(String args[]) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
PrintWriter write = new PrintWriter(System.out);
HashMap<String, History> playerlist = new HashMap<String, History>();
String name = "";
int score;
int max = Integer.MIN_VALUE;
int T = Integer.parseInt(read.readLine());
for(int i = 0; i < T; i++)
{
String[] line = read.readLine().split(" ");
name = line[0];
score = Integer.parseInt(line[1]);
if(playerlist.get(name) ==null)
{
History player = new History(i, score);
playerlist.put(name, player);
}
else
{
History temp = playerlist.get(name);
temp.Update(i,score);
playerlist.put(name, temp);
}
}
for(String key : playerlist.keySet())
{
max = Math.max(max, playerlist.get(key).CurrentScore);
}
String winner = "";
int winninground = T;
for(String key : playerlist.keySet())
{
if(playerlist.get(key).CurrentScore >= max)
{
if(playerlist.get(key).roundpassedMax(max) < winninground)
{
winner = key;
winninground = playerlist.get(key).roundpassedMax(max);
}
}
}
write.print(winner);
write.close();
}
}
| Java | ["3\nmike 3\nandrew 5\nmike 2", "3\nandrew 3\nandrew 2\nmike 5"] | 1 second | ["andrew", "andrew"] | null | Java 8 | standard input | [
"implementation",
"hashing"
] | c9e9b82185481951911db3af72fd04e7 | The first line contains an integer number n (1βββ€ββnβββ€ββ1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive. | 1,500 | Print the name of the winner. | standard output | |
PASSED | 4903e0aa8a6e1392b76f26501e2fd8c1 | train_004.jsonl | 1489851300 | In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1, each either "YES" or "NO". The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise). The string s2 describes a group of soldiers 2 through kβ+β1. And so on, till the string snβ-βkβ+β1 that describes a group of soldiers nβ-βkβ+β1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing namesΒ β it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution. | 256 megabytes | //Do what you can't.
import java.io.*;
import java.util.*;
import java.math.BigInteger;
public class R405A {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = in.nextInt(), k = in.nextInt();
boolean[] rp = new boolean[n];
for (int i = k - 1; i < n; i++)
rp[i] = in.readString().equals("NO");
String[] sa=new String[n];
for (int i = 0; i < n; i++) {
if (!rp[i]) {
sa[i]=gen(i);
} else {
sa[i]=sa[(i - k + 1)];
}
w.print(sa[i]+" ");
}
w.close();
}
static String gen(int n) {
return ((char) ('A' + n / 2) + "" + (char)('a' + n % 26));
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | Java | ["8 3\nNO NO YES YES YES NO", "9 8\nYES NO", "3 2\nNO NO"] | 1 second | ["Adam Bob Bob Cpqepqwer Limak Adam Bob Adam", "R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc", "Na Na Na"] | NoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output: First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is "NO". Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is "NO". Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is "YES". ..., Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is "NO". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 046d6f213fe2d565bfa5ce537346da4f | The first line of the input contains two integers n and k (2ββ€βkββ€βnββ€β50)Β β the number of soldiers and the size of a group respectively. The second line contains nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1. The string si is "YES" if the group of soldiers i through iβ+βkβ-β1 is effective, and "NO" otherwise. | 1,500 | Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them. | standard output | |
PASSED | 12f82e79956fb8011de195c07c113421 | train_004.jsonl | 1489851300 | In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1, each either "YES" or "NO". The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise). The string s2 describes a group of soldiers 2 through kβ+β1. And so on, till the string snβ-βkβ+β1 that describes a group of soldiers nβ-βkβ+β1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing namesΒ β it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.TreeSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Rene
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
boolean[] effective = new boolean[n - k + 1];
for (int i = 0; i < n - k + 1; i++) {
effective[i] = in.next().compareTo("YES") == 0;
}
TreeSet<String> names = new TreeSet<>();
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 26; j++) {
names.add("A" + (char) ('a' + i) + "" + (char) ('a' + j));
}
}
String[] result = new String[n];
boolean seenYes = false;
for (int i = 0; i < n - k + 1; i++) {
if (effective[i]) {
seenYes = true;
TreeSet<String> available = new TreeSet<>(names);
for (int j = 0; j < k; j++) {
if (result[i + j] != null) available.remove(result[i + j]);
}
for (int j = 0; j < k; j++) {
if (result[i + j] == null) result[i + j] = available.pollFirst();
}
} else {
if (!seenYes) result[i] = names.first();
else result[i + k - 1] = result[i];
}
}
if (!seenYes) {
for (int i = 0; i < n; i++) result[i] = names.first();
}
// System.out.println(Arrays.toString(result));
// boolean[] cmp = check(result, k);
// if (!Arrays.equals(cmp, effective)) {
// System.out.println(Arrays.toString(result));
// throw new RuntimeException("wrong");
//// System.out.println("WRONG");
// }
for (String s : result) out.print(s + " ");
out.println();
}
}
static class InputReader implements InputInterface {
public InputStream stream;
private int current;
private int size;
private byte[] buffer = new byte[10000];
public InputReader(InputStream stream) {
this.stream = stream;
current = 0;
size = 0;
}
public InputReader() {
}
public String next() {
StringBuilder sb = new StringBuilder();
int c = readNextValid();
while (!isEmpty(c)) {
sb.append((char) c);
c = read();
}
return sb.toString();
}
int read() {
int result;
try {
if (current >= size) {
current = 0;
size = stream.read(buffer);
if (size < 0) return -1;
}
} catch (IOException e) {
throw new RuntimeException();
}
return buffer[current++];
}
public int nextInt() {
int sign = 1;
int result = 0;
int c = readNextValid();
if (c == '-') {
sign = -1;
c = read();
}
do {
if (c < '0' || c > '9') throw new RuntimeException();
result = 10 * result + c - '0';
c = read();
} while (!isEmpty(c));
result *= sign;
return result;
}
private int readNextValid() {
int result;
do {
result = read();
} while (isEmpty(result));
return result;
}
private boolean isEmpty(int c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == -1;
}
}
static interface InputInterface {
}
}
| Java | ["8 3\nNO NO YES YES YES NO", "9 8\nYES NO", "3 2\nNO NO"] | 1 second | ["Adam Bob Bob Cpqepqwer Limak Adam Bob Adam", "R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc", "Na Na Na"] | NoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output: First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is "NO". Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is "NO". Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is "YES". ..., Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is "NO". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 046d6f213fe2d565bfa5ce537346da4f | The first line of the input contains two integers n and k (2ββ€βkββ€βnββ€β50)Β β the number of soldiers and the size of a group respectively. The second line contains nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1. The string si is "YES" if the group of soldiers i through iβ+βkβ-β1 is effective, and "NO" otherwise. | 1,500 | Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them. | standard output | |
PASSED | 8e156103301c7b4b7c5453db4019854a | train_004.jsonl | 1489851300 | In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1, each either "YES" or "NO". The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise). The string s2 describes a group of soldiers 2 through kβ+β1. And so on, till the string snβ-βkβ+β1 that describes a group of soldiers nβ-βkβ+β1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing namesΒ β it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution. | 256 megabytes | import java.io.OutputStreamWriter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int k = in.nextInt();
String[] a = new String[n + 1];
for (int i = 0; i < k; ++i) {
a[i] = toName(i);
}
for (int i = k; i <= n; ++i) {
String s = in.nextToken();
if (s.equals("YES"))
a[i] = toName(i);
else
a[i] = a[i - k + 1];
}
for (int i = 1; i <= n; ++i)
out.print(a[i] + " ");
out.printLine();
}
private String toName(int x) {
StringBuilder sb = new StringBuilder();
sb.append('A');
while (x > 0) {
sb.append((char)('a' + x % 26));
x /= 26;
}
return sb.toString();
}
}
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 String nextToken() {
int c = readSkipSpace();
StringBuilder sb = new StringBuilder();
while (!isSpace(c)) {
sb.append((char) c);
c = read();
}
return sb.toString();
}
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 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 | ["8 3\nNO NO YES YES YES NO", "9 8\nYES NO", "3 2\nNO NO"] | 1 second | ["Adam Bob Bob Cpqepqwer Limak Adam Bob Adam", "R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc", "Na Na Na"] | NoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output: First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is "NO". Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is "NO". Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is "YES". ..., Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is "NO". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 046d6f213fe2d565bfa5ce537346da4f | The first line of the input contains two integers n and k (2ββ€βkββ€βnββ€β50)Β β the number of soldiers and the size of a group respectively. The second line contains nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1. The string si is "YES" if the group of soldiers i through iβ+βkβ-β1 is effective, and "NO" otherwise. | 1,500 | Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them. | standard output | |
PASSED | 5e1004a590385c137c6d3e9a05de941c | train_004.jsonl | 1489851300 | In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1, each either "YES" or "NO". The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise). The string s2 describes a group of soldiers 2 through kβ+β1. And so on, till the string snβ-βkβ+β1 that describes a group of soldiers nβ-βkβ+β1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing namesΒ β it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution. | 256 megabytes | import java.util.*;
public class Main {
public static final String[] names1 = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"};
public static final String[] names2 = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"};
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
scan.nextLine();
String[] groups = scan.nextLine().split(" ");
LinkedList<String> soldiers = new LinkedList<>();
int soldierIndex = 0;
for (int i = 0; i < groups.length; i++) {
if(groups[i].equalsIgnoreCase("Yes")) {
if(soldierIndex == 0) {
for (int j = 0; j < k; j++) {
soldiers.add((names1[soldierIndex/10] + names2[soldierIndex%10]));
soldierIndex++;
}
} else {
soldiers.add((names1[soldierIndex/10] + names2[soldierIndex%10]));
soldierIndex++;
}
} else {
if(soldierIndex == 0) {
for (int j = 0; j < k-1; j++) {
soldiers.add((names1[soldierIndex/10] + names2[soldierIndex%10]));
soldierIndex++;
}
soldiers.add(soldiers.get(soldiers.size()-k+1));
soldierIndex++;
} else {
soldiers.add(soldiers.get(soldiers.size()-k+1));
soldierIndex++;
}
}
}
for (String name : soldiers) {
System.out.print(name + " ");
}
}
}
| Java | ["8 3\nNO NO YES YES YES NO", "9 8\nYES NO", "3 2\nNO NO"] | 1 second | ["Adam Bob Bob Cpqepqwer Limak Adam Bob Adam", "R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc", "Na Na Na"] | NoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output: First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is "NO". Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is "NO". Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is "YES". ..., Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is "NO". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 046d6f213fe2d565bfa5ce537346da4f | The first line of the input contains two integers n and k (2ββ€βkββ€βnββ€β50)Β β the number of soldiers and the size of a group respectively. The second line contains nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1. The string si is "YES" if the group of soldiers i through iβ+βkβ-β1 is effective, and "NO" otherwise. | 1,500 | Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them. | standard output | |
PASSED | d220aa1a847e53571bff8e5d9f5ebba5 | train_004.jsonl | 1489851300 | In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1, each either "YES" or "NO". The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise). The string s2 describes a group of soldiers 2 through kβ+β1. And so on, till the string snβ-βkβ+β1 that describes a group of soldiers nβ-βkβ+β1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing namesΒ β it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution. | 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
*
* @author Hieu Le
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int nSolders = in.nextInt();
int groupSize = in.nextInt();
boolean[] isEffective = new boolean[nSolders - groupSize + 1];
int index = -1;
for (int i = 0; i < isEffective.length; ++i) {
isEffective[i] = (in.next().equals("YES"));
if (isEffective[i]) {
index = i;
}
}
String[] names = new String[nSolders];
if (index == -1) {
// All groups are ineffective.
Arrays.fill(names, "Foo");
} else {
for (int i = index; i < index + groupSize; ++i) {
names[i] = generateNewName(i);
}
int length = groupSize - 1;
for (int i = index + groupSize; i < names.length; ++i) {
int start = i - groupSize + 1;
if (isEffective[start]) {
names[i] = generateNewName(i);
} else {
names[i] = names[start];
}
}
for (int i = index - 1; i >= 0; --i) {
if (isEffective[i]) {
names[i] = generateNewName(i);
} else {
names[i] = names[i + groupSize - 1];
}
}
}
for (String name : names) {
out.print(name + " ");
}
out.println();
}
private static String generateNewName(int index) {
return "" + (char) ('A' + index / 26) + (char) ('a' + index % 26);
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
private static final int BUFFER_SIZE = 32768;
public InputReader(InputStream stream) {
reader = new BufferedReader(
new InputStreamReader(stream), BUFFER_SIZE);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["8 3\nNO NO YES YES YES NO", "9 8\nYES NO", "3 2\nNO NO"] | 1 second | ["Adam Bob Bob Cpqepqwer Limak Adam Bob Adam", "R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc", "Na Na Na"] | NoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output: First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is "NO". Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is "NO". Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is "YES". ..., Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is "NO". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 046d6f213fe2d565bfa5ce537346da4f | The first line of the input contains two integers n and k (2ββ€βkββ€βnββ€β50)Β β the number of soldiers and the size of a group respectively. The second line contains nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1. The string si is "YES" if the group of soldiers i through iβ+βkβ-β1 is effective, and "NO" otherwise. | 1,500 | Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them. | standard output | |
PASSED | 0e4d3ace4f803f2794f815d9a8b9f63e | train_004.jsonl | 1489851300 | In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1, each either "YES" or "NO". The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise). The string s2 describes a group of soldiers 2 through kβ+β1. And so on, till the string snβ-βkβ+β1 that describes a group of soldiers nβ-βkβ+β1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing namesΒ β it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
ABearAndDifferentNames solver = new ABearAndDifferentNames();
solver.solve(1, in, out);
out.close();
}
}
static class ABearAndDifferentNames {
char[] name = new char[2];
{
name[0] = 'A';
name[1] = 'a';
}
private String name() {
String ans = String.valueOf(name);
name[0]++;
if (name[0] > 'Z') {
name[0] = 'A';
name[1]++;
}
return ans;
}
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.readInt();
int k = in.readInt();
String[] names = new String[n];
for (int i = 0; i < k - 1; i++) {
names[i] = name();
}
for (int i = k - 1; i < n; i++) {
if (in.readString().equals("YES")) {
names[i] = name();
} else {
names[i] = names[i - (k - 1)];
}
}
for (String s : names) {
out.println(s);
}
}
}
static class FastInput {
private final InputStream is;
private StringBuilder defaultStringBuf = new StringBuilder(1 << 13);
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public String readString(StringBuilder builder) {
skipBlank();
while (next > 32) {
builder.append((char) next);
next = read();
}
return builder.toString();
}
public String readString() {
defaultStringBuf.setLength(0);
return readString(defaultStringBuf);
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
public FastOutput append(CharSequence csq) {
cache.append(csq);
return this;
}
public FastOutput append(CharSequence csq, int start, int end) {
cache.append(csq, start, end);
return this;
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput append(char c) {
cache.append(c);
return this;
}
public FastOutput append(String c) {
cache.append(c);
return this;
}
public FastOutput println(String c) {
return append(c).println();
}
public FastOutput println() {
cache.append(System.lineSeparator());
return this;
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
}
| Java | ["8 3\nNO NO YES YES YES NO", "9 8\nYES NO", "3 2\nNO NO"] | 1 second | ["Adam Bob Bob Cpqepqwer Limak Adam Bob Adam", "R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc", "Na Na Na"] | NoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output: First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is "NO". Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is "NO". Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is "YES". ..., Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is "NO". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 046d6f213fe2d565bfa5ce537346da4f | The first line of the input contains two integers n and k (2ββ€βkββ€βnββ€β50)Β β the number of soldiers and the size of a group respectively. The second line contains nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1. The string si is "YES" if the group of soldiers i through iβ+βkβ-β1 is effective, and "NO" otherwise. | 1,500 | Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them. | standard output | |
PASSED | cf56572a1a6cd00e8ca8a0c1f7f58223 | train_004.jsonl | 1489851300 | In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1, each either "YES" or "NO". The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise). The string s2 describes a group of soldiers 2 through kβ+β1. And so on, till the string snβ-βkβ+β1 that describes a group of soldiers nβ-βkβ+β1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing namesΒ β it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
String getName(int x) {
StringBuilder sb = new StringBuilder();
do {
int ch = x % 26;
x /= 26;
if (sb.length() == 0) {
sb.append((char) ('A' + ch));
} else {
sb.append((char) ('a' + ch));
}
} while (0 < x);
return sb.toString();
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
// for (int i = 0; i < 100; i++) {
// out.printLine(getName(i));
// }
int n = in.readInt();
int k = in.readInt();
String[] ans = new String[n];
int word = 0;
for (int i = 0; i < n - k + 1; i++) {
char ch = in.readString().charAt(0);
if (ch == 'Y') {
if (i == 0) {
for (int j = 0; j < k; j++) {
ans[j] = getName(word++);
}
} else {
ans[i + k - 1] = getName(word++);
}
} else if (ch == 'N') {
if (i == 0) {
ans[0] = getName(word);
ans[1] = getName(word);
++word;
for (int j = 2; j < k; j++) {
ans[j] = getName(word++);
}
} else {
ans[i + k - 1] = ans[i];
}
} else {
throw new RuntimeException();
}
}
out.printLine(ans);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int 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 {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["8 3\nNO NO YES YES YES NO", "9 8\nYES NO", "3 2\nNO NO"] | 1 second | ["Adam Bob Bob Cpqepqwer Limak Adam Bob Adam", "R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc", "Na Na Na"] | NoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output: First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is "NO". Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is "NO". Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is "YES". ..., Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is "NO". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 046d6f213fe2d565bfa5ce537346da4f | The first line of the input contains two integers n and k (2ββ€βkββ€βnββ€β50)Β β the number of soldiers and the size of a group respectively. The second line contains nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1. The string si is "YES" if the group of soldiers i through iβ+βkβ-β1 is effective, and "NO" otherwise. | 1,500 | Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them. | standard output | |
PASSED | 98c7cba5f7a52b013efb48473cab7742 | train_004.jsonl | 1489851300 | In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1, each either "YES" or "NO". The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise). The string s2 describes a group of soldiers 2 through kβ+β1. And so on, till the string snβ-βkβ+β1 that describes a group of soldiers nβ-βkβ+β1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing namesΒ β it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Objects;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Zayakin Andrey
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Input in = new Input(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, Input in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
int words = n - k + 1;
String[] w = new String[words];
for (int i = 0; i < w.length; i++) {
w[i] = in.nextToken();
}
int cur = 1;
String[] names = new String[n];
for (int i = 0; i < k; i++) {
names[i] = decode(cur++);
}
if (Objects.equals(w[0], "YES")) {
} else {
names[1] = names[0];
}
int pos = k;
for (int i = 1; i < words; i++) {
if (Objects.equals(w[i], "YES")) {
names[pos] = decode(cur++);
} else {
names[pos] = names[pos - k + 1];
}
pos++;
}
for (int i = 0; i < n; i++) {
out.print(names[i] + " ");
}
}
private String decode(int cur) {
String s = "";
while (cur > 0) {
s += Character.toString((char) (cur % 26 + 'a'));
cur /= 26;
}
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
}
static class Input {
private StringTokenizer tokenizer = null;
private BufferedReader reader;
public Input(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException();
}
}
public String nextToken() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(nextLine());
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
}
}
| Java | ["8 3\nNO NO YES YES YES NO", "9 8\nYES NO", "3 2\nNO NO"] | 1 second | ["Adam Bob Bob Cpqepqwer Limak Adam Bob Adam", "R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc", "Na Na Na"] | NoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output: First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is "NO". Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is "NO". Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is "YES". ..., Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is "NO". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 046d6f213fe2d565bfa5ce537346da4f | The first line of the input contains two integers n and k (2ββ€βkββ€βnββ€β50)Β β the number of soldiers and the size of a group respectively. The second line contains nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1. The string si is "YES" if the group of soldiers i through iβ+βkβ-β1 is effective, and "NO" otherwise. | 1,500 | Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them. | standard output | |
PASSED | 6915ed7dbfd7a7ca5d6caa97cb2f0949 | train_004.jsonl | 1489851300 | In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1, each either "YES" or "NO". The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise). The string s2 describes a group of soldiers 2 through kβ+β1. And so on, till the string snβ-βkβ+β1 that describes a group of soldiers nβ-βkβ+β1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing namesΒ β it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
BufferedReader in;
StringTokenizer st;
PrintWriter out;
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws Exception {
return Integer.parseInt(next());
}
long nextLong() throws Exception {
return Long.parseLong(next());
}
double nextDouble() throws Exception {
return Double.parseDouble(next());
}
String[] names = { "Vasya", "Petya", "Kolya", "Dimon", "Sanya", "Mike", "Jeka", "Boka", "Joka", "Gena" };
void solve() throws Exception {
int n = nextInt();
int k = nextInt();
String ans[] = new String[n];
for (int i = 0; i < n; i++) {
if (i < k - 1)
ans[i] = names[i % 10] + ((char) ('a' + (i % 15))) + ((char) ('a' + (i / 15)));
else {
String type = next();
if (type.equals("YES"))
ans[i] = names[i % 10] + ((char) ('a' + (i % 15))) + ((char) ('a' + (i / 15)));
else
ans[i] = ans[i - k + 1];
}
out.print(ans[i] + " ");
}
}
void run() {
try {
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
new A().run();
}
}
| Java | ["8 3\nNO NO YES YES YES NO", "9 8\nYES NO", "3 2\nNO NO"] | 1 second | ["Adam Bob Bob Cpqepqwer Limak Adam Bob Adam", "R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc", "Na Na Na"] | NoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output: First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is "NO". Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is "NO". Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is "YES". ..., Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is "NO". | Java 8 | standard input | [
"constructive algorithms",
"greedy"
] | 046d6f213fe2d565bfa5ce537346da4f | The first line of the input contains two integers n and k (2ββ€βkββ€βnββ€β50)Β β the number of soldiers and the size of a group respectively. The second line contains nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1. The string si is "YES" if the group of soldiers i through iβ+βkβ-β1 is effective, and "NO" otherwise. | 1,500 | Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them. | standard output | |
PASSED | 00e2473a24c2da5b42352f4902467c56 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes |
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author Madi
*/
public class Round48A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
int[] k = new int[n];
ArrayList<String> ar = new ArrayList<String>();
for (int i = 0; i < n; i++) {
String a = sc.nextLine();
String b = sc.nextLine();
String[] x = new String[4];
x[0] = a + b;
x[1] = b.charAt(0) + "" + a.charAt(0) + "" + b.charAt(1) + "" + a.charAt(1) + "";
x[2] = b.charAt(1) + "" + b.charAt(0) + "" + a.charAt(1) + "" + a.charAt(0) + "";
x[3] = a.charAt(1) + "" + b.charAt(1) + "" + a.charAt(0) + "" + b.charAt(0) + "";
boolean t = false;
for (int r = 0; r < ar.size(); r++) {
String s = ar.get(r);
for (int j = 0; j < 4; j++) {
if (x[j].equalsIgnoreCase(s)) {
//k[r]++;
t = true;
break;
}
}
if (t) {
break;
}
}
if (!t) {
ar.add(x[0] + "");
//k[ar.size() - 1]++;
}
if (i < n - 1) {
String pp = sc.nextLine();
}
}
System.out.println(ar.size());
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 6cdfefbd0fcae5fc6c8530a506aa7d58 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Solution
{
BufferedReader in;
PrintWriter out;
StringTokenizer ss;
String _token()throws IOException
{
while (!ss.hasMoreTokens())ss=new StringTokenizer(in.readLine());
return ss.nextToken();
}
int _int()throws IOException
{
return Integer.parseInt(_token());
}
long _long()throws IOException
{
return Long.parseLong(_token());
}
double _double()throws IOException
{
return Double.parseDouble(_token());
}
void dbg(String s){System.out.println(s);}
BigInteger a(BigInteger A, BigInteger B){return A.add(B);}
BigInteger m(BigInteger A, BigInteger B){return A.multiply(B);}
BigInteger s(BigInteger A, BigInteger B){return A.subtract(B);}
BigInteger d(BigInteger A, BigInteger B){return A.divide(B);}
void rot(int n)
{
char b[][] = new char[2][2];
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
b[i][j]=a[n][i][j];
a[n][0][0]=b[0][1];
a[n][0][1]=b[1][1];
a[n][1][1]=b[1][0];
a[n][1][0]=b[0][0];
}
char a[][][];
void RUN()throws IOException
{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
ss = new StringTokenizer(" ");
int n = _int();
a =new char[n][2][2];
int ans=0;
for(int i=0;i<n;i++)
{
String s=_token();
if (s.charAt(0)=='*')
s=_token();
a[i][0]=s.toCharArray();
s=_token();
a[i][1]=s.toCharArray();
boolean un = true;
for(int j=0;j<i;j++)
{
for(int t=0;t<4;t++)
{
rot(j);
boolean eq=true;
for(int k=0;k<2;k++)
for(int l=0;l<2;l++)
eq&=a[i][k][l]==a[j][k][l];
un&=!eq;
}
}
if (un)
ans++;
}
out.println(ans);
out.close();
}
public static void main(String[] args)throws Exception
{
try {new Solution().RUN();}catch (Exception e){System.out.println("RE");};
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 8f64951910d932d3e27d57e1b579546e | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class Prob051A
{
public static void main( String[] Args )
{
Scanner scan = new Scanner( System.in );
int numDominoes = scan.nextInt();
ArrayList<Amulet> al = new ArrayList<Amulet>();
al.add( new Amulet( scan.nextInt(), scan.nextInt() ) );
for ( int x = 1; x < numDominoes; x++ )
{
scan.next();
Amulet temp = new Amulet( scan.nextInt(), scan.nextInt() );
if ( al.indexOf( temp ) < 0 )
al.add( temp );
}
System.out.println( al.size() );
}
}
class Amulet
{
int value;
public Amulet( int a, int b )
{
value = Integer.MAX_VALUE;
int[] digits = { a / 10, a % 10, b % 10, b / 10 };
for ( int x = 0; x < digits.length; x++ )
{
int temp = 0;
for ( int y = x; y < digits.length + x; y++ )
temp = temp * 10 + digits[y % digits.length];
value = Math.min( value, temp );
}
}
@Override
public boolean equals( Object obj )
{
if ( obj == this )
return true;
if ( obj == null || obj.getClass() != this.getClass() )
return false;
Amulet other = (Amulet)obj;
return value == other.value;
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | de050f8f92ea8b16538b67958494d20a | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.util.*;
public class C48A {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String str1=new String();
String str2=new String();
String str3=new String();
String s[]=new String[n];
for(int i=0;i<n;i++){
str1=sc.next();
str2=sc.next();
if(i!=n-1)
str3=sc.next();
s[i]=str1+str2;
}
int count=1;
int c[]=new int[n];
int cc=0;
int sum=n;
boolean f=false;
String sss[]=new String[4];
int res=0;
for(int i=0;i<n;i++){
sss[0]=s[i];
sss[1]=String.valueOf(String.valueOf(s[i].charAt(2))+String.valueOf(s[i].charAt(0))+String.valueOf(s[i].charAt(3))+String.valueOf(s[i].charAt(1)));
sss[2]=String.valueOf(String.valueOf(s[i].charAt(3))+String.valueOf(s[i].charAt(2))+String.valueOf(s[i].charAt(1))+String.valueOf(s[i].charAt(0)));
sss[3]=String.valueOf(String.valueOf(s[i].charAt(1))+String.valueOf(s[i].charAt(3))+String.valueOf(s[i].charAt(0))+String.valueOf(s[i].charAt(2)));
count=1;
for(int j=i+1;j<n;j++){
f=false;
for(int t=0;t<cc;t++){
if(c[t]==j){
f=true;
break;
}
}
if(!f){
for(int k=0;k<4;k++){
if(s[j].equals(sss[k])){
c[cc++]=j;
count++;
break;
}
}
}
}
if(count>1){
res++;
sum=sum-count;
}
}
System.out.println(sum+res);
}//main
}//class
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 795cd78ecc4d54ace26c8d4cb2f2fb42 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.*;
public class A{
private BufferedReader in;
private StringTokenizer st;
boolean valid(int[][]g1,int[][]g2){
return g1[0][0] == g2[0][0] && g1[0][1] == g2[0][1] && g1[1][0] == g2[1][0] && g1[1][1] == g2[1][1];
}
int[][]rotat(int[][]g2){
int [][] r = new int[2][2];
r[0][0] = g2[0][1];
r[0][1] = g2[1][1];
r[1][0] = g2[0][0];
r[1][1] = g2[1][0];
return r;
}
boolean match(int[][]g1,int[][]g2){
if(valid(g1,g2)) return true;
g2 = rotat(g2);
if(valid(g1,g2)) return true;
g2 = rotat(g2);
if(valid(g1,g2)) return true;
g2 = rotat(g2);
if(valid(g1,g2)) return true;
return false;
}
void solve() throws IOException{
ArrayList<int[][]> g = new ArrayList<int[][]>();
int n = nextInt();
int[]x = new int[n];
int c = 1;
int sz = 0;
while(n-->0){
int a = nextInt();
int b = nextInt();
if(n!=0)
next();
int[][]g1 = new int[2][2];
g1[0][0] = a/10;
g1[0][1] = a%10;
g1[1][0] = b/10;
g1[1][1] = b%10;
// System.out.println(a/10);
// System.out.println(a%10);
// System.out.println(g1[1][0]);
// System.out.println(g1[1][1]);
boolean f = false;
// System.out.println(n);
for (int i = 0; i < g.size(); i++) {
if(match(g1,g.get(i))){
f = true;
x[sz++] = x[i];
break;
}
}
if(!f){
x[sz++] = c;
c++;
}
g.add(g1);
}
int max = 0;
for (int i = 0; i < x.length; i++) {
max = Math.max(x[i], max);
}
System.out.println(max);
}
A() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
eat("");
solve();
}
private void eat(String str) {
st = new StringTokenizer(str);
}
String next() throws IOException {
while (!st.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
eat(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) throws IOException {
new A();
}
int gcd(int a,int b){
if(b>a) return gcd(b,a);
if(b==0) return a;
return gcd(b,a%b);
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 758400ab7b5e389748014b93f54a189f | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.util.*;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
ArrayList<int[][]> squares = new ArrayList<int[][]>();
while(sc.hasNextLine()) {
int[][] square = new int[2][2];
String s = sc.nextLine();
square[0][0] = s.charAt(0) - '0';
square[0][1] = s.charAt(1) - '0';
s = sc.nextLine();
square[1][0] = s.charAt(0) - '0';
square[1][1] = s.charAt(1) - '0';
squares.add(square);
if (sc.hasNextLine())
sc.nextLine();
}
boolean[] checked = new boolean[squares.size()];
int cnt = 0;
for (int i = 0; i < squares.size(); i++) {
if (!checked[i]) {
cnt++;
int[][] cur = squares.get(i);
for (int j = i + 1; j < squares.size(); j++) {
if (isSame(cur, squares.get(j)))
checked[j] = true;
}
}
}
System.out.println(cnt);
}
public static boolean isSame(int[][] s1, int[][] s2) {
if (s1[0][0] == s2[0][0] && s1[0][1] == s2[0][1] && s1[1][0] == s2[1][0] && s1[1][1] == s2[1][1])
return true;
if (s1[0][0] == s2[0][1] && s1[0][1] == s2[1][1] && s1[1][0] == s2[0][0] && s1[1][1] == s2[1][0])
return true;
if (s1[0][0] == s2[1][1] && s1[0][1] == s2[1][0] && s1[1][0] == s2[0][1] && s1[1][1] == s2[0][0])
return true;
if (s1[0][0] == s2[1][0] && s1[0][1] == s2[0][0] && s1[1][0] == s2[1][1] && s1[1][1] == s2[0][1])
return true;
return false;
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 295a1d3212f1f1750e724528862b5d15 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
MyScanner in;
PrintWriter out;
final static String filename = "";
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner(String file) {
try {
br = new BufferedReader(new FileReader(file));
st = new StringTokenizer("");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
st = new StringTokenizer("");
}
String nextToken() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(this.nextToken());
}
double nextDouble() {
return Double.parseDouble(this.nextToken());
}
long nextLong() {
return Long.parseLong(this.nextToken());
}
void close() throws IOException {
br.close();
}
}
int[] a;
int n;
boolean eq(String s1, String s2, String p1, String p2) {
boolean ans = false;
if (s1.equals(p1) && s2.equals(p2))
ans = true;
if (s1.charAt(0) == p1.charAt(1) &&
s1.charAt(1) == p2.charAt(1) &&
s2.charAt(1) == p2.charAt(0) &&
s2.charAt(0) == p1.charAt(0))
ans = true;
if (s1.charAt(0) == p2.charAt(1) &&
s1.charAt(1) == p2.charAt(0) &&
s2.charAt(1) == p1.charAt(0) &&
s2.charAt(0) == p1.charAt(1))
ans = true;
if (s1.charAt(0) == p2.charAt(0) &&
s1.charAt(1) == p1.charAt(0) &&
s2.charAt(1) == p1.charAt(1) &&
s2.charAt(0) == p2.charAt(1))
ans = true;
return ans;
}
void solve() throws IOException {
n = in.nextInt();
String[] a1 = new String[n];
String[] a2 = new String[n];
int cnt = 0;
for (int i = 0; i < n; i++) {
a1[i] = in.nextToken();
a2[i] = in.nextToken();
boolean t = false;
for (int j = 0; j < i; j++)
if (eq(a1[i], a2[i], a1[j], a2[j]))
t = true;
if (!t)
cnt++;
if (i < n - 1) {
String trash = in.nextToken();
}
}
out.println(cnt);
}
void run() {
try {
in = new MyScanner(System.in);
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) {
new A().run();
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | d6aeeba91fb5cce0365f48561313a4e2 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class A implements Runnable {
// leave empty to read from stdin/stdout
private static final String TASK_NAME_FOR_IO = "";
// file names
private static final String FILE_IN = TASK_NAME_FOR_IO + ".in";
private static final String FILE_OUT = TASK_NAME_FOR_IO + ".out";
BufferedReader in;
PrintWriter out;
StringTokenizer tokenizer = new StringTokenizer("");
public static void main(String[] args) {
new Thread(new A()).start();
}
int n, answer;
class Domino {
int a1, a2;
int b1, b2;
Domino(int a1, int a2, int b1, int b2) {
this.a1 = a1;
this.a2 = a2;
this.b1 = b1;
this.b2 = b2;
}
public Domino(String s, String t) {
this(s.charAt(0), s.charAt(1), t.charAt(0), t.charAt(1));
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object o) {
Domino that = (Domino) o;
for (int i = 0; i < 4; i++) {
if (this.a1 == that.a1 && this.a2 == that.a2 && this.b1 == that.b1 && this.b2 == that.b2) {
return true;
}
that = that.rotate();
}
return false;
}
public Domino rotate() {
return new Domino(b1, a1, b2, a2);
}
}
private void solve() throws IOException {
n = nextInt();
Set<Domino> set = new HashSet<Domino>();
for (int i = 0; i < n; i++) {
String s = nextToken();
if (s.contains("*")) {
s = nextToken();
}
String t = nextToken();
Domino d = new Domino(s, t);
set.add(d);
}
out.print(set.size());
}
public void run() {
long timeStart = System.currentTimeMillis();
try {
if (TASK_NAME_FOR_IO.length() > 0) {
in = new BufferedReader(new FileReader(FILE_IN));
out = new PrintWriter(new FileWriter(FILE_OUT));
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
}
solve();
in.close();
out.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
long timeEnd = System.currentTimeMillis();
System.out.println("Time spent: " + (timeEnd - timeStart) + " ms");
}
private String nextToken() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private BigInteger nextBigInt() throws IOException {
return new BigInteger(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | b61475e581d8fc019c02f0d71d912250 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes |
import java.util.*;
public class A
{
public static void main(String[] args)
{
new A(new Scanner(System.in));
}
public A(Scanner in)
{
int N = in.nextInt();
int res = 0;
TreeSet<String> ts = new TreeSet<String>();
while (N-->0)
{
int[][] tab = new int[2][2];
for (int j=0; j<2; j++)
{
String s = in.next();
for (int i=0; i<2; i++)
tab[i][j] = (int)(s.charAt(i)-'0');
}
if (in.hasNext()) in.next();
for (int u=0; u<4; u++)
{
StringBuilder sb = new StringBuilder();
for (int j=0; j<2; j++)
for (int i=0; i<2; i++)
sb.append(tab[i][j]);
if (ts.add(sb.toString())&&(u==0))
res++;
int[][] nxt = new int[2][2];
nxt[0][0] = tab[1][0];
nxt[1][0] = tab[1][1];
nxt[1][1] = tab[0][1];
nxt[0][1] = tab[0][0];
tab = nxt;
}
}
//System.out.println(ts);
System.out.printf("%d%n", res);
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 53d2e050b32900056c2ce1c7249ff57e | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class A {
public static boolean isEqual(char[][] x, char[][] y) {
shift(y);
if (equal(x, y))
return true;
shift(y);
if (equal(x, y))
return true;
shift(y);
if (equal(x, y))
return true;
shift(y);
if (equal(x, y))
return true;
return false;
}
public static void shift(char[][] x) {
char temp = x[0][0];
x[0][0] = x[0][1];
x[0][1] = x[1][1];
x[1][1] = x[1][0];
x[1][0] = temp;
}
public static boolean equal(char[][] x, char[][] y) {
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
if (x[i][j] != y[i][j])
return false;
return true;
}
public static void read(char[][] x, BufferedReader in) throws IOException {
for (int i = 0; i < 2; i++)
x[i] = in.readLine().toCharArray();
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
char[][][] A = new char[n][2][2];
read(A[0], in);
for (int i = 1; i < n; i++) {
in.readLine();
read(A[i], in);
}
int ans = 0;
boolean[] visited = new boolean[n];
for (int i = 0; i < n; i++)
if (!visited[i]) {
ans++;
for (int j = i + 1; j < n; j++)
if (isEqual(A[i], A[j]))
visited[j] = true;
}
System.out.println(ans);
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 86d992a1d829f83b931d0121c892cfe2 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Trung Pham
*/
public class A {
public static void main(String[] args) {
Scanner in = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
Amulet[] data = new Amulet[n];
for (int i = 0; i < n; i++) {
String a = in.next();
StringBuilder builder = new StringBuilder();
builder.append(in.next());
a += builder.reverse().toString();
data[i] = new Amulet();
String val = a;
// System.out.println(val);
for (int j = 0; j < 4; j++) {
data[i].num[j] = val.charAt(j) - '0';
}
if (i + 1 < n) {
in.next();
}
}
boolean[] count = new boolean[n];
int result = 0;
for (int i = 0; i < n; i++) {
if (!count[i]) {
result++;
for (int j = i + 1; j < n; j++) {
for (int k = 0; k < 4; k++) {
boolean found = true;
for (int h = 0; h < 4; h++) {
int index = (k + h) % 4;
if (data[i].num[h] != data[j].num[index]) {
found = false;
break;
}
}
if (found) {
count[j] = true;
break;
}
}
}
}
}
out.println(result);
out.close();
}
public static class Amulet {
int[] num = new int[4];
}
static class FT {
int[] data;
FT(int n) {
data = new int[n];
}
void update(int index, int val) {
// System.out.println("UPDATE INDEX " + index);
while (index < data.length) {
data[index] += val;
index += index & (-index);
// System.out.println("NEXT " +index);
}
}
int get(int index) {
// System.out.println("GET INDEX " + index);
int result = 0;
while (index > 0) {
result += data[index];
index -= index & (-index);
// System.out.println("BACK " + index);
}
return result;
}
}
static int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
static int pow(int a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
int val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val;
} else {
return val * val * a;
}
}
// static Point intersect(Point a, Point b, Point c) {
// double D = cross(a, b);
// if (D != 0) {
// return new Point(cross(c, b) / D, cross(a, c) / D);
// }
// return null;
// }
//
// static Point convert(Point a, double angle) {
// double x = a.x * cos(angle) - a.y * sin(angle);
// double y = a.x * sin(angle) + a.y * cos(angle);
// return new Point(x, y);
// }
static Point minus(Point a, Point b) {
return new Point(a.x - b.x, a.y - b.y);
}
static Point add(Point a, Point b) {
return new Point(a.x + b.x, a.y + b.y);
}
static double cross(Point a, Point b) {
return a.x * b.y - a.y * b.x;
}
static class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point: " + x + " " + y;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
//System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
}
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 | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | c21ac8c1f324fa2ad2ffc74f54d290ab | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class A {
static BufferedReader IN;
static {
try {
// IN = new BufferedReader(new FileReader(new File(A.class.getResource("a2.txt").toURI())));
IN = new BufferedReader(new InputStreamReader(System.in));
}
catch(Exception e) {
e.printStackTrace();
}
}
static String inStr() {
try {
return IN.readLine();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
static int inInt() { return Integer.parseInt(inStr()); }
static int[] inIntArr() {
String s = inStr();
if(s == null)
return null;
return toIntArr(s);
}
static int[] toIntArr(String s) {
String[] sArr = s.split(" ");
int[] iArr = new int[sArr.length];
for(int i = 0; i < sArr.length; ++i)
iArr[i] = Integer.parseInt(sArr[i]);
return iArr;
}
static void out(String s) { System.out.println(s); }
static void out(int i) { out(Integer.toString(i)); }
public static void main(String[] args) {
int n = inInt();
Set<Integer> unique = new HashSet<Integer>();
for(int i = 0; i < n; ++i) {
int x = Integer.parseInt(inStr());
int y = Integer.parseInt(inStr());
x = x*100 + 10*(y%10) + y/10;
int x2 = 10*(x%1000) + x/1000;
int x3 = 10*(x2%1000) + x2/1000;
int x4 = 10*(x3%1000) + x3/1000;
int min = Math.min(Math.min(x3, x4), Math.min(x, x2));
unique.add(Integer.valueOf(min));
inStr();
}
out(unique.size());
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 90e86248dd7023e70998fe8bee675973 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.util.*;
import java.io.*;
public class test
{
public static void main(String[] args)
{
new test().run();
}
void run()
{
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
HashSet<String> hs = new HashSet<String>();
int count = 0;
for (int i = 0; i < n; i++)
{
if (i != 0)
in.next();
char[] l1 = in.next().toCharArray();
char[] l2 = in.next().toCharArray();
if (!hs.contains("" + l1[0] + l1[1] + l2[0] + l2[1]))
{
count++;
hs.add("" + l1[0] + l1[1] + l2[0] + l2[1]);
hs.add("" + l2[0] + l1[0] + l2[1] + l1[1]);
hs.add("" + l2[1] + l2[0] + l1[1] + l1[0]);
hs.add("" + l1[1] + l2[1] + l1[0] + l2[0]);
}
}
out.println(count);
out.close();
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 555f185dcc46fc9c001dd39c7a760fb0 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.util.Scanner;
public class Main {
static class Amulet{
public int one,two,thre,four;
public boolean stay = false;
public Amulet(int one, int two, int thre, int four) {
this.one = one;
this.two = two;
this.thre = thre;
this.four = four;
}
public void rotate(){
int aa1,aa2,aa3,aa4;
aa1 = one;
aa2 = two;
aa3 = thre;
aa4 = four;
one = two;
two = four;
thre = aa1;
four = aa3;
}
}
public static int cntN,cntStop;
public static int[][][][] Mas;
public static Amulet[] ams;
public static void main(String[] args) {
Mas = new int[17][27][37][47];
Scanner sc = new Scanner(System.in);
StringBuilder strB = new StringBuilder();
int i=1;
int r[];
r = new int [5];
String strR;
ams = new Amulet[10001];
int CNT = 0;
if(sc.hasNext()) {
CNT = sc.nextInt();
}
int ccc = CNT;
while(sc.hasNext()&&CNT>0){
strR = sc.next();
if(!strR.equals("**")){
r[i++] = Integer.parseInt(String.valueOf(strR.charAt(0)));
r[i++] = Integer.parseInt(String.valueOf(strR.charAt(1)));
if(i==5){
ams[CNT--] = new Amulet(r[1], r[2], r[3], r[4]);
}
} else i = 1;
}
for(i=1;i<=ccc;i++){
if(!ams[i].stay){
if(Mas[10+ams[i].one][20+ams[i].two][30+ams[i].thre][40+ams[i].four]==0) cntStop++;
Mas[10+ams[i].one][20+ams[i].two][30+ams[i].thre][40+ams[i].four]+=1;
ams[i].stay = true;
}
for(int j = i+1;j<=ccc;j++){
if(!ams[j].stay){
int k=0;
for(k=0;k<4;k++){
if(Mas[10+ams[j].one][20+ams[j].two][30+ams[j].thre][40+ams[j].four]!=0){
Mas[10+ams[j].one][20+ams[j].two][30+ams[j].thre][40+ams[j].four]++;
ams[j].stay =true;
break;
}
ams[j].rotate();
}
if(k==4){
Mas[10+ams[j].one][20+ams[j].two][30+ams[j].thre][40+ams[j].four]++;
ams[j].stay =true;
cntStop++;
}
}
}
}
System.out.print(cntStop);
}
} | Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | cfa4b4f504b8d55e5e56c0729ffcab47 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
void solve() throws IOException {
int n = rInt();
TreeSet<String> trr = new TreeSet<String>();
for (int i = 0; i < n; i++){
String [] arr = new String[4];
int a = rInt();
int b = rInt();
b = b % 10 * 10 + b / 10;
int c = 100 * a + b;
arr[0] = String.valueOf(c);
for (int j = 0; j < 3; j++){
c = c % 1000 * 10 + c / 1000;
arr[j + 1] = String.valueOf(c);
}
Arrays.sort(arr);
String s = arr[0] + arr[1] + arr[2] + arr[3];
trr.add(s);
if (i!= n - 1){
String st = rNext();
}
}
//while(!trset.isEmpty())out.println(trset.pollLast());
out.println(trr.size());
}
public static void main(String args[]) throws Exception {
long start = System.currentTimeMillis();
new Main().run();
System.err.println("Time = " + ((System.currentTimeMillis() - start) / 1000.) + " s.");
}
StringTokenizer st;
PrintWriter out;
BufferedReader br;
void run() throws IOException {
Locale.setDefault(Locale.US);
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
String name = "a";
//br = new BufferedReader(new FileReader(name + ".in"));
//out = new PrintWriter(new FileWriter(name + ".out"));
solve();
out.flush();
}
String rNext() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int rInt() throws IOException {
return Integer.parseInt(rNext());
}
long rLong() throws IOException {
return Long.parseLong(rNext());
}
double rDouble() throws IOException {
return Double.parseDouble(rNext());
}
String rLine() throws IOException {
return br.readLine();
}
void dbg(Object... os) throws IOException {
System.err.println(Arrays.deepToString(os));
}
} | Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 393dc50c1c8325769bcf6745466fff72 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.*;
public class CheateriusProblem {
public static boolean check(String a, String b) {
ArrayList<String> strings = new ArrayList<String>();
strings.add(b);
String c = "";
for(int i = 3; i >= 0; --i) c += b.charAt(i);
strings.add(c);
String d = "" + b.charAt(2) + b.charAt(0) + b.charAt(3) + b.charAt(1);
strings.add(d);
c = "";
for(int i = 3; i >= 0; --i) c += d.charAt(i);
strings.add(c);
for(String s : strings) {
if(s.equals(a))
return true;
}
//System.out.println(strings.toString());
return false;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
//Scanner sc = new Scanner(new FileReader("A.txt"));
int n = sc.nextInt();
String s[] = new String[n];
Arrays.fill(s, "");
for(int i = 0; i < n; ++i) {
for(int j = 0; j < 2; ++j) {
s[i] = s[i].concat(sc.next());
}
if(i != n - 1)
sc.next();
}
//System.out.println(Arrays.toString(s));
boolean[] used = new boolean[n];
int count = 0;
for(int i = 0; i < n; ++i) {
if(!used[i]) {
for(int j = i + 1; j < n; ++j) {
if(!used[j] && check(s[i], s[j]))
used[j] = true;
}
}
}
//System.out.println(Arrays.toString(used));
for(boolean ok : used)
if(!ok)
count++;
System.out.println(count);
sc.close();
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 7910d1a6f9ae33a2f4fc964934696876 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | //package round48;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Scanner;
public class A {
Scanner in;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[][] am = new int[n][4];
for(int i = 0;i < n;i++){
String str = in.next();
am[i][0] = str.charAt(0) - '0';
am[i][1] = str.charAt(1) - '0';
str = in.next();
am[i][2] = str.charAt(0) - '0';
am[i][3] = str.charAt(1) - '0';
if(i < n - 1)in.next();
}
BitSet aned = new BitSet();
for(int i = aned.nextClearBit(0);i < n;i = aned.nextClearBit(i+1)){
int a = am[i][0], b = am[i][1], c = am[i][2], d = am[i][3];
for(int j = aned.nextClearBit(i+1);j < n;j = aned.nextClearBit(j+1)){
int e = am[j][0], f = am[j][1], g = am[j][2], h = am[j][3];
if(e==a && f==b && g==c && h==d)aned.set(j);
if(e==b && f==d && g==a && h==c)aned.set(j);
if(e==d && f==c && g==b && h==a)aned.set(j);
if(e==c && f==a && g==d && h==b)aned.set(j);
}
}
out.println(n - aned.cardinality());
}
void run() throws Exception
{
in = INPUT.isEmpty() ? new Scanner(System.in) : new Scanner(INPUT);
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception
{
new A().run();
}
int ni() { return Integer.parseInt(in.next()); }
void tr(Object... o) { if(INPUT.length() != 0)System.out.println(o.length > 1 || o[0].getClass().isArray() ? Arrays.deepToString(o) : o[0]); }
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | f80efd3a23e5f7c09305bb5971daf02d | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes |
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
List<Integer>[] a = new List[n];
for(int i = 0; i < n; ++i) {
a[i] = new ArrayList<Integer>();
for(int j = 0; j < 2; ++j) {
int b = in.nextInt();
if(j == 0) {
a[i].add(b/10);
a[i].add(b%10);
} else {
a[i].add(b%10);
a[i].add(b/10);
}
}
if(i != n-1) in.next();
}
Set<List<Integer>> unique = new HashSet<List<Integer>>();
for(List<Integer> list : a) {
boolean good = true;
for(int rot = 0; rot < 4; ++rot) {
Collections.rotate(list,-1);
//System.out.println(list.get(0)+" "+list.get(1)+" "+list.get(2)+" "+list.get(3));
if(unique.contains(list)) good = false;
}
if(good) unique.add(list);
}
System.out.println(unique.size());
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 22b4b4bde9da64897773202a4803a505 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.*;
public class a
{
private static void solve() throws Exception
{
int n = Integer.parseInt(in.readLine());
Set<String> cnt = new HashSet<String>();
for (int i = 0; i < n; i++) {
String t = in.readLine();
String s = in.readLine();
char a = t.charAt(0);
char b = t.charAt(1);
char c = s.charAt(0);
char d = s.charAt(1);
if (!cnt.contains(""+a+b+d+c) && !cnt.contains(""+c+a+b+d) &&
!cnt.contains(""+d+c+a+b) && !cnt.contains(""+b+d+c+a))
{
cnt.add(""+a+b+d+c);
}
in.readLine();
}
out.println(cnt.size());
}
public static void main(String[] args) throws Exception
{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.flush();
}
private static BufferedReader in;
private static PrintWriter out;
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | ce7d28f7f2fcb714818fbcf359878bec | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes |
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
public class a {
static class amul {
int ur, ul, dr, dl;
public amul(int ulx, int urx, int drx, int dlx) {
ur = urx;
ul = ulx;
dr = drx;
dl = dlx;
}
public int hashCode() {
int[] ar=new int[]{ur,ul,dr,dl};
Arrays.sort(ar);
return ar[0] + ar[1] * 101 + ar[2] *101 * 101 + ar[3] * 101 * 101 * 101;
}
public boolean equals(Object r) {
amul x = (amul) r;
int [] init=new int[]{x.ul,x.ur,x.dr,x.dl};
for(int i=0;i<4;i++) {
if(init[0]==ul&&init[1]==ur&&init[2]==dr&&init[3]==dl) return true;
int tmp=init[3];
init[3]=init[2];
init[2]=init[1];
init[1]=init[0];
init[0]=tmp;
}
return false;
}
}
public static void rotate(int[] x) {
int tmp=x[3];
x[3]=x[2];
x[2]=x[1];
x[1]=x[0];
x[0]=tmp;
}
public static void main(String[] args) {
HashSet<amul> set = new HashSet<a.amul>();
Scanner sc = new Scanner(System.in);
int amu = sc.nextInt();
for (int i = 0; i < amu; i++) {
String f = sc.next();
String s = sc.next();
set.add(new amul(f.charAt(0) - '0', f.charAt(1) - '0',
s.charAt(1) - '0', s.charAt(0) - '0'));
if(i<amu-1)
sc.next();
}
System.out.println(set.size());
}
} | Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | db527280c8a848bec31ac0170626dbdc | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Cheateriu {
static InputStreamReader inp = new InputStreamReader(System.in);
static BufferedReader in = new BufferedReader(inp);
static boolean test = false;
static PrintWriter writer = new PrintWriter(System.out);
static String testDataFile = "testdata.txt";
BufferedReader reader = null;
public Cheateriu() throws Throwable {
if (test) {
reader = new BufferedReader(new FileReader(new File(testDataFile)));
}
}
private void solve() throws Throwable {
int bricks = readInteger();
int[][] vals = new int[bricks][4];
for (int i = 0; i < bricks; i++) {
String s = readLine();
int[] a = new int[] { s.charAt(0) - '0', s.charAt(1) - '0' };
s = readLine();
int[] b = new int[] { s.charAt(0) - '0', s.charAt(1) - '0' };
if (i < bricks - 1) {
readLine();
}
vals[i][0] = a[0];
vals[i][1] = a[1];
vals[i][2] = b[1];
vals[i][3] = b[0];
}
boolean[] marked = new boolean[bricks];
int count = 0;
for (int i = 0; i < bricks; i++) {
if (marked[i]) {
continue;
}
marked[i] = true;
count++;
for (int j = i + 1; j < bricks; j++) {
for (int j2 = 0; j2 < 4; j2++) {
boolean match = true;
for (int k = 0; k < 4; k++) {
// System.out.println(j2);
// System.out.println(j);
// System.out.println(j2);
if (vals[i][k] != vals[j][(j2 + k) % 4]) {
match = false;
break;
}
}
if (match) {
marked[j] = true;
break;
}
}
}
}
System.out.println(count);
}
/**
* The I/O method of reading
*/
int id = -1;
public String readLine() throws IOException {
id++;
if (test)
return reader.readLine();
else
return in.readLine();
}
/**
* read a single integer should be a full line
*/
private int readInteger() throws NumberFormatException, IOException {
return Integer.valueOf(readLine());
}
/**
* Read one line and split contents to an int array
*/
private int[] readIntegers() throws Exception {
String[] split = readLine().split(" ");
int[] list = new int[split.length];
for (int i = 0; i < list.length; i++) {
list[i] = Integer.parseInt(split[i]);
}
return list;
}
/**
* Entry point
*/
public static void main(String[] args) throws Throwable {
new Cheateriu().solve();
}
} | Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 2b590e08740f1f237e962d37b1870c26 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.*;
public class A
{
String line;
StringTokenizer inputParser;
BufferedReader is;
FileInputStream fstream;
DataInputStream in;
void openInput(String file)
{
if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
else
{
try{
fstream = new FileInputStream(file);
in = new DataInputStream(fstream);
is = new BufferedReader(new InputStreamReader(in));
}catch(Exception e)
{
System.err.println(e);
}
}
}
void readNextLine()
{
try {
line = is.readLine();
inputParser = new StringTokenizer(line, " ");
//System.err.println("Input: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
int NextInt()
{
String n = inputParser.nextToken();
int val = Integer.parseInt(n);
//System.out.println("I read this number: " + val);
return val;
}
String NextString()
{
String n = inputParser.nextToken();
return n;
}
void closeInput()
{
try {
is.close();
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
public static void main(String [] argv)
{
String filePath=null;
if(argv.length>0)filePath=argv[0];
A a = new A(filePath);
}
public A(String inputFile)
{
openInput(inputFile);
readNextLine();
ArrayList <Pile> p = new ArrayList <Pile>();
int N=NextInt();
for(int i=0; i<N; i++)
{
readNextLine();
int a=NextInt();
int b=a%10;
a=a/10;
readNextLine();
int d=NextInt();
int c=d%10;
d/=10;
boolean needed=true;
for(int j=0; j<p.size()&&needed; j++)
{
if(p.get(j).isSame(a, b, c, d))needed=false;
}
if(needed)
{
Pile pile = new Pile(a, b, c, d);
p.add(pile);
}
if(i+1<N)readNextLine();
}
System.out.println(p.size());
}
private class Pile
{
int a,b,c,d;
Pile(int a, int b, int c, int d)
{
this.a=a;
this.b=b;
this.c=c;
this.d=d;
}
public boolean isSame(int a, int b, int c, int d)
{
if(this.a==a&&this.b==b&&this.c==c&&this.d==d)return true;
if(this.a==b&&this.b==c&&this.c==d&&this.d==a)return true;
if(this.a==c&&this.b==d&&this.c==a&&this.d==b)return true;
if(this.a==d&&this.b==a&&this.c==b&&this.d==c)return true;
return false;
}
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | f0caa9c1b1a40c8e30a5f73b6668e8aa | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int x=Integer.parseInt(br.readLine());
ArrayList<String> sa=new ArrayList<String>();
String st=br.readLine()+invert(br.readLine());
sa.add(st);boolean bol=false;
while(br.ready()){br.readLine();
st=br.readLine()+invert(br.readLine());
for (int j = 0; j <sa.size(); j++) {
String y=sa.get(j)+sa.get(j); bol=true;;
if(y.contains(st)){bol=false;break;}
}
if(bol)sa.add(st);
}
System.out.println(sa.size());
}
public static String invert(String x){
String t=""+x.charAt(1)+x.charAt(0);return t;
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 1ff0875ca5b8d464beea228a89e7a475 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class A {
public static void main(String[] args) throws NumberFormatException,
IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = new Integer(in.readLine());
char[][] a = new char[n][4];
for (int i = 0; i < a.length; i++) {
String s = in.readLine();
String t = in.readLine();
if (i + 1 < a.length)
in.readLine();
a[i] = (s + t.charAt(1) + t.charAt(0)).toCharArray();
}
int[] v = new int[n];
int p = 0;
for (int i = 0; i < a.length; i++) {
if (v[i] == 0)
p++;
for (int j = 0; j < a.length; j++) {
if (i != j) {
if (ok(a[i], a[j]))
v[i] = v[j] = p;
}
}
}
System.out.println(p);
}
private static boolean ok(char[] a, char[] b) {
for (int d = 1; d <= 4; d++) {
boolean ok = true;
for (int i = 0; i < b.length; i++) {
if (a[i] != b[(i + d) % 4])
ok = false;
}
if (ok)
return true;
}
return false;
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | cbf866e9bb9db9e824e5e3ae570552de | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | //package round48;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class D {
static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter out = new PrintWriter(System.out);
static String nextToken() throws IOException{
while (st==null || !st.hasMoreTokens()){
String s = bf.readLine();
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
static int nextInt() throws IOException{
return Integer.parseInt(nextToken());
}
static String nextStr() throws IOException{
return nextToken();
}
static double nextDouble() throws IOException{
return Double.parseDouble(nextToken());
}
static boolean cmp(byte s1[], byte s2[], int shift){
for (int i=0; i<4; i++)
if (s1[i] != s2[(i+shift)%4])
return false;
return true;
}
public static void main(String[] args) throws IOException{
int n = nextInt(),
k = 0;
byte p[][] = new byte[n][];
for (int i=0; i<n; i++){
byte s[] = new byte[4];
byte s1[] = nextStr().getBytes();
byte s2[] = nextStr().getBytes();
String tmp = "";
if (i != n-1)
tmp = nextStr();
s[0] = s1[0];
s[1] = s1[1];
s[2] = s2[1];
s[3] = s2[0];
boolean add = true;
for (int l=0; l<k; l++)
for (int j=0; j<4; j++)
if (cmp(s, p[l], j))
add = false;
if (add)
p[k++] = s;
}
out.println(k);
out.flush();
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | d92270ad3d6f5f87cd7528fb2389ae25 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class ProblemA_48 {
final boolean ONLINE_JUDGE=System.getProperty("ONLINE_JUDGE")!=null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok=new StringTokenizer("");
void init() throws FileNotFoundException{
if (ONLINE_JUDGE){
in=new BufferedReader(new InputStreamReader(System.in));
out =new PrintWriter(System.out);
}
else{
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException{
while(!tok.hasMoreTokens()){
tok=new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException{
return Integer.parseInt(readString());
}
public static void main(String[] args){
new ProblemA_48().run();
}
class Charm implements Comparable<Charm>{
public int[] p=new int[4];
public Charm(){
for (int i=0; i<4; i++){
p[i]=0;
}
}
@Override
public int compareTo(Charm arg0) {
for (int i=0; i<4; i++){
if ((this.p[i]==arg0.p[0])&&(this.p[(i+1)%4]==arg0.p[1])&&(this.p[(i+2)%4]==arg0.p[2])&&(this.p[(i+3)%4]==arg0.p[3])){
return 0;
}
}
return -1;
}
}
public void run(){
try{
long t1=System.currentTimeMillis();
init();
solve();
out.close();
long t2=System.currentTimeMillis();
System.err.println("Time = "+(t2-t1));
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
void solve() throws IOException{
int n=readInt();
Charm[] a=new Charm[n];
for (int i=0; i<n; i++){
a[i]=new Charm();
}
for (int i=0; i<3*n-1; i++){
String s=readString();
if (i%3==0){
a[i/3].p[0]=s.charAt(0)-'0';
a[i/3].p[1]=s.charAt(1)-'0';
}
if (i%3==1){
a[i/3].p[3]=s.charAt(0)-'0';
a[i/3].p[2]=s.charAt(1)-'0';
}
}
boolean[] b=new boolean[n];
Arrays.fill(b, false);
int k=0;
for (int i=0; i<n; i++){
if (!b[i]){
k++;
for (int j=0; j<n; j++){
if (a[i].compareTo(a[j])==0){
b[j]=true;
}
}
}
}
out.print(k);
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 719b792f90a907c769cf952dcbd2f152 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.*;
//Codeforces Beta Round #48 (Div. 1), A
public class CheateriusProblem {
private static class Amulet {
final char dominos[];
public Amulet(char dominos[]) {
this.dominos = dominos;
}
@Override
public boolean equals(Object o) {
return o instanceof Amulet && equals((Amulet)o);
}
public boolean equals(Amulet o) {
assert dominos.length == o.dominos.length;
for(int i = 0; i < dominos.length; i++) {
if(equals(o.dominos, i))
return true;
}
return false;
}
private boolean equals(char dominos[], int start) {
for(int i = 0; i < this.dominos.length; i++) {
if(this.dominos[i] != dominos[(start + i) % dominos.length])
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 0;
for(int i = 0; i < dominos.length; i++)
hash += dominos[i];
return hash;
}
}
public static void main(String[] args) throws IOException {
File file = new File("input.txt");
if(file.exists())
System.setIn(new FileInputStream(file));
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(r.readLine());
Set<Amulet> set = new HashSet<Amulet>();
for(int i = 0; i < n; i++) {
if(i != 0) {
String s = r.readLine();
assert s.equals("**");
}
String s1 = r.readLine(), s2 = r.readLine();
assert s1.length() == 2 && s2.length() == 2;
set.add(new Amulet(new StringBuilder(s1).reverse().append(s2).toString().toCharArray()));
}
System.out.println(set.size());
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | f8a6e8c225536cee4bfca33e4d736ac7 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.*;
//Codeforces Beta Round #48 (Div. 1), A
public class CheateriusProblem {
private static class Amulet {
final char dominos[];
public Amulet(char dominos[]) {
this.dominos = dominos;
}
@Override
public boolean equals(Object o) {
return o instanceof Amulet && equals((Amulet)o);
}
public boolean equals(Amulet o) {
assert dominos.length == o.dominos.length;
for(int i = 0; i < dominos.length; i++) {
if(equals(o.dominos, i))
return true;
}
return false;
}
private boolean equals(char dominos[], int start) {
for(int i = 0; i < this.dominos.length; i++) {
if(this.dominos[i] != dominos[(start + i) % dominos.length])
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 0;
for(int i = 0; i < dominos.length; i++)
hash += dominos[i];
return hash;
}
}
public static void main(String[] args) throws IOException {
File file = new File("input.txt");
if(file.exists())
System.setIn(new FileInputStream(file));
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(r.readLine());
Set<Amulet> set = new HashSet<Amulet>();
for(int i = 0; i < n; i++) {
if(i != 0) {
String s = r.readLine();
assert s.equals("**");
}
String s1 = r.readLine(), s2 = r.readLine();
assert s1.length() == 2 && s2.length() == 2;
set.add(new Amulet(new StringBuilder(s1).reverse().append(s2).toString().toCharArray()));
}
System.out.println(set.size());
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | a78321c459a1aac76fae40ef3a3e7564 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.util.*;
public class Amulets {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int count = 0;
HashSet<String> hs = new HashSet<String>();
for (int i = 0; i < N; i++)
{
int x = sc.nextInt();
int x1 = x / 10;
int x2 = x % 10;
int y = sc.nextInt();
int x3 = y % 10;
int x4 = y / 10;
if (sc.hasNext())
{
sc.nextLine();
sc.nextLine();
}
if (!hs.contains(x1 + " " +x2 + " " + x3 + " " + x4))
{
hs.add(x1 + " " +x2 + " " + x3 + " " + x4);
hs.add(x2 + " " +x3 + " " + x4 + " " + x1);
hs.add(x3 + " " +x4 + " " + x1 + " " + x2);
hs.add(x4 + " " +x1 + " " + x2 + " " + x3);
count++;
}
}
System.out.println(count);
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | e8addda905b5c0b31fb491beb268ec88 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class Main {
class Amulet implements Comparable<Amulet> {
char[][] a;
public Amulet(char x1, char x2, char x3, char x4) {
super();
a = new char[2][2];
a[0][0] = x1;
a[0][1] = x2;
a[1][0] = x3;
a[1][1] = x4;
}
@Override
public int compareTo(Amulet b) {
if (a[0][0] == b.a[0][0] && a[0][1] == b.a[0][1]
&& a[1][1] == b.a[1][1] && a[1][0] == b.a[1][0])
return 0;
if (a[0][0] == b.a[0][1] && a[0][1] == b.a[1][1]
&& a[1][1] == b.a[1][0] && a[1][0] == b.a[0][0])
return 0;
if (a[0][0] == b.a[1][1] && a[0][1] == b.a[1][0]
&& a[1][1] == b.a[0][0] && a[1][0] == b.a[0][1])
return 0;
if (a[0][0] == b.a[1][0] && a[0][1] == b.a[0][0]
&& a[1][1] == b.a[0][1] && a[1][0] == b.a[1][1])
return 0;
return 1;
}
}
class UF {
int n;
int[] p;
void init(int n) {
this.n = n;
p = new int[n];
for (int i = 0; i < n; i++)
p[i] = i;
}
int find(int x) {
while (x != p[x])
x = p[x];
return x;
}
void union(int x, int y) {
x = find(x);
y = find(y);
p[x] = y;
}
int size() {
Set<Integer> s = new HashSet<Integer>();
for (int i = 0; i < n; i++)
s.add(find(i));
return s.size();
}
}
void solve() throws IOException {
int n = nextInt();
Amulet[] amulets = new Amulet[n];
for (int i = 0; i < n; i++) {
String s1 = next();
String s2 = next();
if (i < n - 1)
next();
amulets[i] = new Amulet(s1.charAt(0), s1.charAt(1), s2.charAt(0),
s2.charAt(1));
}
UF uf = new UF();
uf.init(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
if (i != j && amulets[i].compareTo(amulets[j]) == 0)
uf.union(i, j);
}
out.println(uf.size());
}
private BufferedReader in;
private PrintWriter out;
private StringTokenizer st;
Main() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
eat("");
solve();
in.close();
out.close();
}
private void eat(String str) {
st = new StringTokenizer(str);
}
String next() throws IOException {
while (!st.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
eat(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) throws IOException {
new Main();
}
} | Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 71f35ccc0a25c3c19d427c5ae7d8bbd7 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | /**
* Created by IntelliJ IDEA.
* User: piyushd
* Date: 12/28/10
* Time: 9:36 PM
* To change this template use File | Settings | File Templates.
*/
public class Pile {
boolean match(int[][] a1, int[][] a2){
boolean ok = false;
if(!ok && a1[0][0] == a2[0][0] && a1[0][1] == a2[0][1] && a1[1][0] == a2[1][0] && a1[1][1] == a2[1][1]) ok = true;
if(!ok && a1[1][0] == a2[0][0] && a1[0][0] == a2[0][1] && a1[1][1] == a2[1][0] && a1[0][1] == a2[1][1]) ok = true;
if(!ok && a1[1][1] == a2[0][0] && a1[1][0] == a2[0][1] && a1[0][1] == a2[1][0] && a1[0][0] == a2[1][1]) ok = true;
if(!ok && a1[0][1] == a2[0][0] && a1[1][1] == a2[0][1] && a1[0][0] == a2[1][0] && a1[1][0] == a2[1][1]) ok = true;
return ok;
}
void run(){
int N = nextInt(), a = -1;
int[][][] amulets = new int[N][2][2];
for(int i = 0; i < N; i++){
a = nextInt();
amulets[i][0][0] = a / 10;
amulets[i][0][1] = a % 10;
a = nextInt();
amulets[i][1][0] = a / 10;
amulets[i][1][1] = a % 10;
if(i < N - 1)next();
}
int ans = 0;
boolean[] used = new boolean[N];
for(int i = 0; i < N; i++)if(!used[i]){
ans++;
for(int j = 0; j < N; j++)
if(!used[j] && match(amulets[i], amulets[j]))used[j] = true;
}
System.out.println(ans);
}
int nextInt(){
try{
int c = System.in.read();
if(c == -1) return c;
while(c != '-' && (c < '0' || '9' < c)){
c = System.in.read();
if(c == -1) return c;
}
if(c == '-') return -nextInt();
int res = 0;
do{
res *= 10;
res += c - '0';
c = System.in.read();
}while('0' <= c && c <= '9');
return res;
}catch(Exception e){
return -1;
}
}
long nextLong(){
try{
int c = System.in.read();
if(c == -1) return -1;
while(c != '-' && (c < '0' || '9' < c)){
c = System.in.read();
if(c == -1) return -1;
}
if(c == '-') return -nextLong();
long res = 0;
do{
res *= 10;
res += c-'0';
c = System.in.read();
}while('0' <= c && c <= '9');
return res;
}catch(Exception e){
return -1;
}
}
double nextDouble(){
return Double.parseDouble(next());
}
String next(){
try{
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while(Character.isWhitespace(c))
c = System.in.read();
do{
res.append((char)c);
}while(!Character.isWhitespace(c=System.in.read()));
return res.toString();
}catch(Exception e){
return null;
}
}
String nextLine(){
try{
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while(c == '\r' || c == '\n')
c = System.in.read();
do{
res.append((char)c);
c = System.in.read();
}while(c != '\r' && c != '\n');
return res.toString();
}catch(Exception e){
return null;
}
}
public static void main(String[] args){
new Pile().run();
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 7015611cd9d13ca6f465907729d806c1 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.HashSet;
import java.util.Scanner;
public class ProblemA {
public static void main(String[] args) {
PrintStream pw = System.out;
Scanner s = new Scanner(System.in);
// Scanner s = new Scanner(new File("amulets.txt"));
int n = s.nextInt();
int c1, c2, c3, c4;
int n1, n2, n3, n4, nm;
String line;
HashSet<Integer> set = new HashSet<Integer>();
for (int i=0; i<n; i++) {
line = s.next();
c1 = line.charAt(0)-'0';
c2 = line.charAt(1)-'0';
line = s.next();
c4 = line.charAt(0)-'0';
c3 = line.charAt(1)-'0';
if (i < n-1)
line = s.next();
n1 = c1*1000 + c2*100 + c3*10 + c4;
n2 = c2*1000 + c3*100 + c4*10 + c1;
n3 = c3*1000 + c4*100 + c1*10 + c2;
n4 = c4*1000 + c1*100 + c2*10 + c3;
nm = Math.max(Math.max(n1, n2), Math.max(n3, n4));
set.add(nm);
}
pw.println(set.size());
}
} | Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 5e505df8b517640907a06aa3ed802988 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Solution {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String turn(String s) {
char[] ret = new char[4];
ret[0] = s.charAt(1);
ret[1] = s.charAt(3);
ret[2] = s.charAt(0);
ret[3] = s.charAt(2);
return new String(ret);
}
void solve() throws IOException {
int n = ni();
String[] v = new String[n];
String[] t = new String[4];
for (int i = 0; i < n; ++i) {
String s = ns() + ns();
for (int j = 0; j < 4; ++j) {
s = turn(s);
t[j] = s;
}
Arrays.sort(t);
v[i] = t[0];
if (i != n - 1)
ns();
}
Arrays.sort(v);
int ret = 0;
for (int i = 1; i < n; ++i)
if (!v[i].equals(v[i - 1]))
++ret;
++ret;
out.println(ret);
}
public Solution() throws IOException {
Locale.setDefault(Locale.US);
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
String ns() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int ni() throws IOException {
return Integer.valueOf(ns());
}
long nl() throws IOException {
return Long.valueOf(ns());
}
double nd() throws IOException {
return Double.valueOf(ns());
}
public static void main(String[] args) throws IOException {
new Solution();
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | e27893297595559b083a0ceee3795372 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.HashSet;
public class p51a {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
HashSet<String> h = new HashSet<String>();
String x = in.readLine()+"";
String y = in.readLine();
h.add(x+y.charAt(1)+y.charAt(0));
for (int i = 1; i < n; i++) {
in.readLine();
x = in.readLine()+"";
y = in.readLine();
x = x+y.charAt(1)+y.charAt(0);
if(h.contains(x))
continue;
if(h.contains(""+x.charAt(1)+x.charAt(2)+x.charAt(3)+x.charAt(0)))
continue;
if(h.contains(""+x.charAt(2)+x.charAt(3)+x.charAt(0)+x.charAt(1)))
continue;
if(h.contains(""+x.charAt(3)+x.charAt(0)+x.charAt(1)+x.charAt(2)))
continue;
h.add(x);
}
System.out.println(h.size());
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 3c3b2f347ac96f756fe2147f310681a7 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Vector;
public class Solution {
public static class Amulet {
public int i1;
public int i2;
public int i3;
public int i4;
public Amulet(int i1, int i2, int i3, int i4) {
this.i1 = i1;
this.i2 = i2;
this.i3 = i3;
this.i4 = i4;
}
}
public static class Pile {
public Amulet rep;
public Pile(Amulet rep) {
this.rep = rep;
}
public boolean belongs(Amulet a) {
return (a.i1 == rep.i1 && a.i2 == rep.i2 && a.i3 == rep.i3 && a.i4 == rep.i4)
|| (a.i2 == rep.i1 && a.i3 == rep.i2 && a.i4 == rep.i3 && a.i1 == rep.i4)
|| (a.i3 == rep.i1 && a.i4 == rep.i2 && a.i1 == rep.i3 && a.i2 == rep.i4)
|| (a.i4 == rep.i1 && a.i1 == rep.i2 && a.i2 == rep.i3 && a.i3 == rep.i4);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
in.nextLine();
Vector<Pile> v = new Vector<Pile>();
for (int i = 0; i < n; i++) {
String s1 = in.nextLine();
String s2 = in.nextLine();
Amulet a = new Amulet(s1.charAt(0) - '0', s1.charAt(1) - '0', s2.charAt(1) - '0', s2.charAt(0) - '0');
boolean contains = false;
for (int j = 0; j < v.size(); j++)
if (v.elementAt(j).belongs(a)) {
contains = true;
break;
}
if (!contains) {
Pile p = new Pile(a);
v.add(p);
}
if (i != n - 1)
in.nextLine();
}
out.print(v.size());
out.close();
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 22e7bd22a59ad213ec290c6591f18c27 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.awt.Point;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
import javax.swing.text.StyledEditorKit.ItalicAction;
import static java.lang.Double.*;
import static java.lang.Integer.*;
import static java.math.BigInteger.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class Main implements Runnable {
private void solve() throws IOException {
// long start = System.currentTimeMillis();
init();
readData();
processing();
}
private void init() {
si = new HashSet<Integer>();
}
private Set<Integer> si;
private void processing() {
println(si.size());
}
private void add(int value) {
si.add(value);
}
private int correct(String row1, String row2) {
String s = row1 + row2;
s = mins(s, row1.charAt(1), row2.charAt(1), row1.charAt(0), row2.charAt(0));
s = mins(s, row2.charAt(1), row2.charAt(0), row1.charAt(1), row1.charAt(0));
s = mins(s, row2.charAt(0), row1.charAt(0), row2.charAt(1), row1.charAt(1));
return Integer.parseInt(s);
}
private String mins(String s1, char ch1, char ch2, char ch3, char ch4) {
String s2 = String.valueOf(ch1);
s2 += ch2;
s2 += ch3;
s2 += ch4;
if (s1.compareTo(s2) < 0) {
return s1;
}
else {
return s2;
}
}
private void readData() throws IOException {
n = nextInt();
for (int i = 0; i < n; ++i) {
String s1 = nextToken();
String s2 = nextToken();
if (i < n-1) {
String noise = nextToken();
}
add(correct(s1, s2));
}
}
private int n;
public static void main(String[] args) throws InterruptedException {
new Thread(null, new Runnable() {
public void run() {
new Main().run();
}
}, "1", 1 << 24).start();
}
// @Override
public void run() {
try {
boolean onlineJudge = System.getProperty("ONLINE_JUDGE") != null;
reader = onlineJudge ? new BufferedReader(new InputStreamReader(
System.in)) : new BufferedReader(
new FileReader("input.txt"));
writer = onlineJudge ? new PrintWriter(new BufferedWriter(
new OutputStreamWriter(System.out))) : new PrintWriter(
new BufferedWriter(new FileWriter("output.txt")));
Locale.setDefault(Locale.US);
tokenizer = null;
solve();
writer.flush();
} catch (Exception error) {
error.printStackTrace();
System.exit(1);
}
}
private BufferedReader reader;
private PrintWriter writer;
private StringTokenizer tokenizer;
private void println() {
writer.println();
}
private void print(long value) {
writer.print(value);
}
private void println(long value) {
writer.println(value);
}
private void print(char ch) {
writer.print(ch);
}
private void println(String s) {
writer.println(s);
}
private void print(String s) {
writer.print(s);
}
private void print(int value) {
writer.print(value);
}
private void println(int value) {
writer.println(value);
}
private void printf(String f, double d) {
writer.printf(f, d);
}
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());
}
private String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
} | Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | a073c7ea862fd3f971f33613244573fa | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.util.*;
import static java.lang.Math.*;
public class Main{
public static void main(String[] args){
new Main().run();
}
void run(){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<String> a = new ArrayList<String>();
for(int i = 0; i < n; i++){
if(i > 0)sc.next();
int head = sc.nextInt();
int tail = sc.nextInt();
String s = "" + head + (tail%10) + (tail/10);
boolean exist = false;
for(int j = 0; !exist && j < a.size(); j++){
exist = check(s, a.get(j));
}
if(!exist)a.add(s);
}
System.out.println(a.size());
}
boolean check(String s, String t){
for(int i = 0; i < s.length(); i++){
String r = s.substring(i) + s.substring(0, i);
if(r.equals(t))return true;
}
return false;
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 4c0bac8d9a8ee4c3bf73f4f0ed6f57b6 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.*;
public class ProblemA {
InputReader in; PrintWriter out;
void solve() {
int n = in.nextInt();
int[] a = new int[10000];
Arrays.fill(a, 0);
for (int i = 0; i < n; i++) {
String s = in.next();
int[] b = new int[4];
b[0] = s.charAt(0) - '0';
b[1] = s.charAt(1) - '0';
s = in.next();
b[3] = s.charAt(0) - '0';
b[2] = s.charAt(1) - '0';
if (i < n - 1)
s = in.next();
int mi = Integer.MAX_VALUE / 3;
for (int j = 0; j < 4; j++) {
int cur = 0;
int st = 1;
for (int k = 0; k < 4; k++) {
cur += b[(k + j) & 3] * st;
st *= 10;
}
if (cur < mi)
mi = cur;
}
a[mi]++;
}
int ans = 0;
for (int i = 0; i < 10000; i++)
if (a[i] > 0) {
// out.println(i);
ans++;
}
out.println(ans);
}
ProblemA(){
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
try {
if (oj) {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
else {
Writer w = new FileWriter("output.txt");
in = new InputReader(new FileReader("input.txt"));
out = new PrintWriter(w);
}
} catch(Exception e) {
throw new RuntimeException(e);
}
solve();
out.close();
}
public static void main(String[] args){
new ProblemA();
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public InputReader(FileReader fr) {
reader = new BufferedReader(fr);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 94ec949eab22a800dfa78f416f32839b | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Main{
static class Run implements Runnable{
//TODO parameters
final boolean consoleIO = true;
final String inFile = "input.txt";
final String outFile = "output.txt";
int n;
Quad[] q;
Pair<Integer,Integer> getNum(String s) {
Pair<Integer,Integer> t = new Pair<Integer,Integer>(0,0);
t.a = Integer.valueOf(s.charAt(0));
t.b = Integer.valueOf(s.charAt(1));
return t;
}
@Override
public void run() {
n = nextInt();
q = new Quad[n];
for(int i = 0; i < n; ++i) {
Pair<Integer,Integer> a = getNum(nextLine());
Pair<Integer,Integer> b = getNum(nextLine());
q[i] = new Quad(a.a,a.b,b.b,b.a);
if(i<n-1)
nextLine();
}
boolean[] visited = new boolean[n];
int count=0;
for(int i = 0; i < n-1; ++i) {
if(visited[i])
continue;
for(int j = i+1; j < n; ++j) {
if(visited[j])
continue;
if(q[i].equals(q[j])) {
visited[j] = true;
continue;
}
Quad tmp = new Quad(q[j].a,q[j].b,q[j].c,q[j].d);
for(int k = 0; k < 3; ++k) {
tmp = tmp.rotate();
if(tmp.equals(q[i])) {
visited[j] = true;
continue;
}
}
}
++count;
visited[i] = true;
}
count += visited[n-1]?0:1;
print(count);
close();
}
class Quad {
int a,b,c,d;
Quad(int a, int b, int c, int d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
Quad rotate() {
Quad t = new Quad(0,0,0,0);
t.a = d;
t.b = a;
t.c = b;
t.d = c;
return t;
}
@Override
public boolean equals(Object obj) {
Quad q = (Quad) obj;
return a==q.a && b==q.b && c==q.c && d==q.d;
}
}
//=========================================================================================================================
BufferedReader in;
PrintWriter out;
StringTokenizer strTok;
Run() {
if (consoleIO) {
initConsoleIO();
}
else {
initFileIO();
}
}
void initConsoleIO() {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
}
void initFileIO() {
try {
in = new BufferedReader(new FileReader(inFile));
out = new PrintWriter(new FileWriter(outFile));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
void close() {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
float nextFloat() {
return Float.parseFloat(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
String nextLine() {
try {
return in.readLine();
} catch (IOException e) {
return "__NULL";
}
}
boolean hasMoreTokens() {
return (strTok == null) || (strTok.hasMoreTokens());
}
String nextToken() {
while (strTok == null || !strTok.hasMoreTokens()) {
String line;
try {
line = in.readLine();
strTok = new StringTokenizer(line);
} catch (IOException e) {
e.printStackTrace();
}
}
return strTok.nextToken();
}
void cout(Object o){
System.out.println(o);
}
void print(Object o) {
out.write(o.toString());
}
void println(Object o) {
out.write(o.toString() + '\n');
}
void printf(String format, Object... args) {
out.printf(format, args);
}
String sprintf(String format, Object... args) {
return MessageFormat.format(format, args);
}
}
static class Pair<A, B> {
A a;
B b;
A f() {
return a;
}
B s() {
return b;
}
Pair(A a, B b) {
this.a = a;
this.b = b;
}
Pair(Pair<A, B> p) {
a = p.f();
b = p.s();
}
}
public static void main(String[] args) throws IOException {
Run run = new Run();
Thread thread = new Thread(run);
thread.run();
}
} | Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | f5a4c1fc7c7934cd4cfea01e007c8d04 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.lang.*;
import java.io.*;
import java.util.*;
import java.math.*;
public class Solution implements Runnable{
private static BufferedReader br = null;
private static PrintWriter out = null;
private static StringTokenizer stk = null;
public static void main(String[] args) {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
(new Thread(new Solution())).start();
}
private void loadLine() {
try {
stk = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
private String nextLine() {
try {
return br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
private Integer nextInt() {
while (stk==null||!stk.hasMoreTokens()) loadLine();
return Integer.parseInt(stk.nextToken());
}
private Long nextLong() {
while (stk==null||!stk.hasMoreTokens()) loadLine();
return Long.parseLong(stk.nextToken());
}
private String nextWord() {
while (stk==null||!stk.hasMoreTokens()) loadLine();
return (stk.nextToken());
}
private Double nextDouble() {
while (stk==null||!stk.hasMoreTokens()) loadLine();
return Double.parseDouble(stk.nextToken());
}
int[] rotate(int[] a) {
int[] res = (int[])a.clone();
for (int i = 0; i < a.length; ++i) {
res[i] = a[(i+1)%a.length];
}
return res;
}
boolean equal(int[] a, int[] b) {
for (int i = 0; i < a.length; ++i) {
if (a[i] != b[i])
return false;
}
return true;
}
public void run() {
int n = nextInt();
int res = 0;
int[][] a = new int[n][4];
for (int i = 0; i < n; ++i) {
int ar = nextInt();
int br = nextInt();
if (i < n-1)
nextLine();
a[i][0] = ar/10;
a[i][1] = ar%10;
a[i][2] = br%10;
a[i][3] = br/10;
}
boolean[] used = new boolean[n];
for (int i = 0; i < n; ++i) {
if (!used[i]) {
++res;
for (int j = i+1; j < n; ++j) {
int[] tmp = a[j].clone();
for (int k = 0; k < 4; ++k) {
if (equal(a[i], tmp)) {
used[j] = true;
break;
}
tmp = rotate(tmp);
}
}
}
}
out.println(res);
out.flush();
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | e3f728c53f0ea4398a65a5ad5aaf1686 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;
public class Main {
public static void main(String[] args) throws IOException {
new Thread(null, new Runnable() {
public void run() {
try {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {}
new Main().run();
} catch (IOException e) {
e.printStackTrace();
}
}
}, "1", 1L << 24).start();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
int N;
Item[] a;
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
N = nextInt();
a = new Item [N];
int ans = 0;
for (int i = 0; i < N; i++) {
char[] s1 = nextToken().toCharArray();
char[] s2 = nextToken().toCharArray();
if (i < N - 1)
nextToken();
a[i] = new Item(s1[0] - '0', s1[1] - '0', s2[0] - '0', s2[1] - '0');
boolean ok = true;
for (int j = 0; j < i; j++) {
if (a[i].equals(a[j])) {
ok = false;
break;
}
}
if (ok)
ans++;
}
out.println(ans);
out.close();
}
class Item {
int[][] v = new int [2][2];
Item(int a, int b, int c, int d) {
v[0][0] = a;
v[0][1] = b;
v[1][0] = c;
v[1][1] = d;
}
@Override
public boolean equals(Object obj) {
Item x = (Item) obj;
return
v[0][0] == x.v[0][0] && v[0][1] == x.v[0][1] && v[1][0] == x.v[1][0] && v[1][1] == x.v[1][1] ||
v[0][0] == x.v[0][1] && v[0][1] == x.v[1][1] && v[1][0] == x.v[0][0] && v[1][1] == x.v[1][0] ||
v[0][0] == x.v[1][1] && v[0][1] == x.v[1][0] && v[1][0] == x.v[0][1] && v[1][1] == x.v[0][0] ||
v[0][0] == x.v[1][0] && v[0][1] == x.v[0][0] && v[1][0] == x.v[1][1] && v[1][1] == x.v[0][1];
}
}
String nextToken() throws IOException {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null) {
return true;
}
st = new StringTokenizer(s);
}
return false;
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | fe43b613d0179f9d2f0f53a3e0c96213 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class m5 {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
char [][][] inp = new char [n][2][2];
for (int i = 0; i < n; i++) {
inp[i][0] = in.readLine().toCharArray();
inp[i][1] = in.readLine().toCharArray();
if(i!=n-1)
in.readLine();
}
int res = 0;
boolean vis [] = new boolean [n];
for (int i = 0; i < inp.length; i++) {
if(vis[i])
continue;
vis[i] = true;
res++;
for (int j = i+1; j < inp.length; j++) {
if(vis[j])
continue;
if(inp[i][0][0]==inp[j][0][0] &&
inp[i][0][1]==inp[j][0][1] &&
inp[i][1][0]==inp[j][1][0] &&
inp[i][1][1]==inp[j][1][1]){
vis[j] = true;
continue;
}
if(inp[i][0][0]==inp[j][0][1] &&
inp[i][0][1]==inp[j][1][1] &&
inp[i][1][0]==inp[j][0][0] &&
inp[i][1][1]==inp[j][1][0]){
vis[j] = true;
continue;
}
if(inp[i][0][0]==inp[j][1][1] &&
inp[i][0][1]==inp[j][1][0] &&
inp[i][1][0]==inp[j][0][1] &&
inp[i][1][1]==inp[j][0][0]){
vis[j] = true;
continue;
}
if(inp[i][0][0]==inp[j][1][0] &&
inp[i][0][1]==inp[j][0][0] &&
inp[i][1][0]==inp[j][1][1] &&
inp[i][1][1]==inp[j][0][1]){
vis[j] = true;
continue;
}
}
}
System.out.println(res);
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 716d3b6ee05a6a1a7b942ad0e97314ce | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
public class Cheatrius{
public static void main(String args[])throws Exception{
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
int i=0,j=0,k=0,n=0,t=0,l=0;
String s1="",s2="",s3="";
n=Integer.parseInt(br.readLine());
String va[][]=new String[n][4];
boolean b=false;
for(i=0;i<n;i++)
{b=false;
s1=br.readLine();
s2=br.readLine();
s1=s1+s2.charAt(1)+s2.charAt(0);
for(j=0;j<t;j++){
for(k=0;k<4;k++)
if(s1.equals(va[j][k]))
{b=true;break;}
if(b)break;
}
if(!b)
{l++;
va[t][0]=s1;
for(j=1;j<=3;j++)
va[t][j]=""+va[t][j-1].charAt(3)+va[t][j-1].substring(0,3);
t++;
}
if(i<n-1)
s1=br.readLine();
}
System.out.println(l);
}} | Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | c46cfa976501af50948eb3e66f346db2 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes |
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class BetaRound48_A implements Runnable {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws IOException {
if (ONLINE_JUDGE) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
@Override
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
public static void main(String[] args) {
new Thread(new BetaRound48_A()).start();
}
void solve() throws IOException {
int n = Integer.parseInt(in.readLine());
int[][] a = new int[n][4];
for (int i = 0; i < n; i++) {
String s = in.readLine();
a[i][0] = s.charAt(0) - '0';
a[i][1] = s.charAt(1) - '0';
s = in.readLine();
a[i][2] = s.charAt(1) - '0';
a[i][3] = s.charAt(0) - '0';
if (i != n-1) in.readLine();
}
int[] p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = i;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (check(a[i], a[j])) {
int d = min(p[i], p[j]);
p[i] = d;
p[j] = d;
}
}
}
HashSet<Integer> set = new HashSet<Integer>();
for (int i = 0; i < n; i++) {
set.add(p[i]);
}
out.print(set.size());
}
boolean check(int[] a, int[] b) {
int q = 0;
for (int k = 0; k < 4; k++) {
for (int i = 0; i < 4; i++) {
if (a[i] == b[(i + k) % 4]) q++;
}
if (q == 4) return true;
q = 0;
}
return false;
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 15402ffed60810aaf027b90079681923 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class Main
{
public static void main(String args[]) throws Exception
{
Solution sol = new Solution();
sol.Run();
}
static class Domino implements Comparable<Domino>
{
private int[] num;
Domino(int[] num)
{
this.num = num;
}
@Override public int compareTo(Domino d)
{
for (int i = 0; i < 4; i++)
{
if (num[i] != d.num[i])
return num[i] - d.num[i];
}
return 0;
}
@Override public String toString()
{
String x = new String();
for (int i = 0; i < 4; i++)
{
x += num[i];
}
return x;
}
}
static public class Solution
{
@SuppressWarnings("unused")
private Scanner scanner;
private final int[] arr = new int[4];
private List<MyInteger> list = new ArrayList<MyInteger>();
public class MyInteger
{
public int integer;
public MyInteger()
{
}
@Override public String toString()
{
return Integer.toString(integer);
}
}
void generate(Map<Domino, MyInteger> map, int step)
{
if (step == 4)
{
Domino d = new Domino(Arrays.copyOf(arr, arr.length));
if (map.containsKey(d))
{
return;
}
int[] cycle = Arrays.copyOf(arr, arr.length);
MyInteger integer = new MyInteger();
list.add(integer);
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
cycle[j] = arr[(j + i) % 4];
}
Domino dd = new Domino(Arrays.copyOf(cycle, cycle.length));
map.put(dd, integer);
}
return;
}
for (int i = 1; i <= 6; i++)
{
arr[step] = i;
generate(map, step + 1);
}
}
void solve(BufferedReader input, PrintStream output) throws Exception
{
Map<Domino, MyInteger> map = new TreeMap<Domino, MyInteger>();
generate(map, 0);
int n = scanner.nextInt();
// output.println("map size = " + map.size());
// output.println("list size = " + list.size());
for (int i = 0; i < n; i++)
{
int a = scanner.nextInt();
int x[] = new int[4];
x[0] = a / 10;
x[1] = a % 10;
a = scanner.nextInt();
x[2] = a % 10;
x[3] = a / 10;
if (i < n - 1)
{
scanner.nextLine();
scanner.nextLine();
}
Domino dd = new Domino(x);
//output.println("value = " + dd);
MyInteger integer = map.get(dd);
integer.integer++;
}
int sum = 0;
for (MyInteger integer : list)
{
if (integer.integer > 0)
{
sum++;
}
}
output.println(sum);
}
void Run() throws Exception
{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader input = new BufferedReader(new FileReader("test.in"));
scanner = new Scanner(input);
PrintStream output = System.out;
solve(input, output);
}
}
} | Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 854699fcf053db908fd0f69a334b82c6 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.TreeSet;
public class Main {
private static StreamTokenizer in;
private static PrintWriter out;
private static BufferedReader inB;
private static int nextInt() throws Exception{
in.nextToken();
return (int)in.nval;
}
private static String nextString() throws Exception{
in.nextToken();
return in.sval;
}
static{
inB = new BufferedReader(new InputStreamReader(System.in));
in = new StreamTokenizer(inB);
out = new PrintWriter(System.out);
}
public static void main(String[] args)throws Exception{
int n = Integer.parseInt(inB.readLine());
int count = 0;
TreeSet<Domino> hs = new TreeSet<Domino>();
ArrayList<Domino> a = new ArrayList<Domino>();
m: for(int i = 0; i<n; i++) {
String s1 = inB.readLine();
String s2 = inB.readLine();
if(i != n-1) {
inB.readLine();
}
Domino d = new Domino(s1.charAt(0) - '0', s1.charAt(1) - '0', s2.charAt(0) - '0', s2.charAt(1) - '0');
for(Domino dd : a) {
if(d.equals(dd))continue m;
}
a.add(d);
count++;
// if(!hs.contains(d)) {
// hs.add(d);
// count++;
// }
}
System.out.println(count);
}
}
class Domino implements Comparable {
int _11, _12;
int _21, _22;
public Domino(int _1,int _2,int _3,int _4) {
_11 = _1; _12 = _2;
_21 = _3; _22 = _4;
}
public boolean eq(Domino d) {
return _11 == d._11 && _12 == d._12 && _21 == d._21 && _22 == d._22;
}
private Domino rot() {
return new Domino(_12, _22, _11, _21);
}
public boolean equals(Domino d) {
if(eq(d))return true;
d = d.rot();
if(eq(d))return true;
d = d.rot();
if(eq(d))return true;
d = d.rot();
if(eq(d))return true;
return false;
}
public int compareTo(Object d) {
return equals((Domino)d)?0:1;
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 63716bdc1de4b5da720d2d65d0ba106f | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class Amulets implements Runnable {
private void solve() throws IOException {
int n = nextInt();
Set<String> res = new HashSet<String>();
for (int i = 0; i < n; ++i) {
if (i > 0) nextToken();
String s = nextToken();
String u = nextToken();
s += u.charAt(1);
s += u.charAt(0);
String t = s;
for (int j = 1; j < 4; ++j) {
String cur = s.substring(j) + s.substring(0, j);
if (cur.compareTo(t) < 0)
t = cur;
}
res.add(t);
}
writer.println(res.size());
}
public static void main(String[] args) {
new Amulets().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | 677024f6488d9ebc41903106e74e57fe | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.*;
public class CheateriusProblem
{
Scanner in;
PrintWriter out;
CheateriusProblem()
{
in = new Scanner(System.in);
out = new PrintWriter(System.out);
}
CheateriusProblem(String o) throws FileNotFoundException
{
in = new Scanner(System.in);
out = new PrintWriter(new File(o));
}
CheateriusProblem(String i, String o) throws FileNotFoundException
{
in = new Scanner(new File(i));
out = new PrintWriter(new File(o));
}
public void finalize()
{
out.flush();
in.close();
out.close();
}
/*
* pq rp sr qs
* rs sq qp pr
*/
void solve()
{
int n = in.nextInt(),
co = 0;
Set<String> set = new HashSet<String>();
for(int i = 0; i < n; ++i)
{
String a = in.next(),
b = in.next();
if(i != n - 1)
{
String s = in.next();
}
char p = a.charAt(0),
q = a.charAt(1),
r = b.charAt(0),
s = b.charAt(1);
String e = p + "" + q + "" + r + "" + s,
f = r + "" + p + "" + s + "" + q,
g = s + "" + r + "" + q + "" + p,
h = q + "" + s + "" + p + "" + r;
if(!set.contains(e) && !set.contains(f) && !set.contains(g) && !set.contains(h))
{
set.add(e);
set.add(f);
set.add(g);
set.add(h);
++co;
}
}
out.println(co);
}
public static void main(String[] args) throws FileNotFoundException
{
CheateriusProblem t = new CheateriusProblem();
t.solve();
t.finalize();
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | fe031ef82903d3a360b8043527c5ace0 | train_004.jsonl | 1293552000 | Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2βΓβ2 which are the Cheaterius' magic amulets! That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2βΓβ2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk. | 256 megabytes | import java.io.*;
import java.util.*;
public class CheateriusProblem
{
Scanner in;
PrintWriter out;
CheateriusProblem()
{
in = new Scanner(System.in);
out = new PrintWriter(System.out);
}
CheateriusProblem(String o) throws FileNotFoundException
{
in = new Scanner(System.in);
out = new PrintWriter(new File(o));
}
CheateriusProblem(String i, String o) throws FileNotFoundException
{
in = new Scanner(new File(i));
out = new PrintWriter(new File(o));
}
public void finalize()
{
out.flush();
in.close();
out.close();
}
/*
* pq rp sr qs
* rs sq qp pr
*/
void solve()
{
int n = in.nextInt(),
co = 0;
Set<String> set = new HashSet<String>();
for(int i = 0; i < n; ++i)
{
String a = in.next(),
b = in.next();
if(i != n - 1)
{
String s = in.next();
}
char p = a.charAt(0),
q = a.charAt(1),
r = b.charAt(0),
s = b.charAt(1);
String e = p + "" + q + "" + r + "" + s,
f = r + "" + p + "" + s + "" + q,
g = s + "" + r + "" + q + "" + p,
h = q + "" + s + "" + p + "" + r;
if(!set.contains(e) && !set.contains(f) && !set.contains(g) && !set.contains(h))
{
set.add(e);
set.add(f);
set.add(g);
set.add(h);
++co;
}
}
out.println(co);
}
public static void main(String[] args) throws FileNotFoundException
{
CheateriusProblem t = new CheateriusProblem();
t.solve();
t.finalize();
}
}
| Java | ["4\n31\n23\n**\n31\n23\n**\n13\n32\n**\n32\n13", "4\n51\n26\n**\n54\n35\n**\n25\n61\n**\n45\n53"] | 2 seconds | ["1", "2"] | null | Java 6 | standard input | [
"implementation"
] | 3de36638239deacac56e104d3dce1670 | The first line contains an integer n (1ββ€βnββ€β1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located. | 1,300 | Print the required number of piles. | standard output | |
PASSED | b17c94542fa6c7dc876ff171a1a75c7a | train_004.jsonl | 1479918900 | Alyona has built n towers by putting small cubes some on the top of others. Each cube has size 1βΓβ1βΓβ1. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row.Sometimes Alyona chooses some segment towers, and put on the top of each tower several cubes. Formally, Alyouna chooses some segment of towers from li to ri and adds di cubes on the top of them.Let the sequence a1,βa2,β...,βan be the heights of the towers from left to right. Let's call as a segment of towers al,βalβ+β1,β...,βar a hill if the following condition holds: there is integer k (lββ€βkββ€βr) such that alβ<βalβ+β1β<βalβ+β2β<β...β<βakβ>βakβ+β1β>βakβ+β2β>β...β>βar.After each addition of di cubes on the top of the towers from li to ri, Alyona wants to know the maximum width among all hills. The width of a hill is the number of towers in it. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.*;
/*
_ooOoo_
o8888888o
88" . "88
(| -_- |)
O\ = /O
____/`---'\____
.' \\| |// `.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' | |
\ .-\__ `-` ___/-. /
___`. .' /--.--\ `. . __
."" '< `.___\_<|>_/___.' >'"".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `-. \_ __\ /__ _/ .-` / /
======`-.____`-.___\_____/___.-`____.-'======
`=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pass System Test!
*/
public class E {
private static class Task {
void solve(FastScanner in, PrintWriter out) throws Exception {
int N = in.nextInt();
long[] a = in.nextLongArray(N);
TreeMap<Integer, Integer> left = new TreeMap<>();
int from = 0;
for (int i = 0; i < N; i++) {
if (i == N - 1 || a[i] >= a[i + 1]) {
left.put(from, i);
from = i + 1;
}
}
TreeMap<Integer, Integer> right = new TreeMap<>();
from = N - 1;
for (int i = N - 2; i >= -1; i--) {
if (i < 0 || a[i] <= a[i + 1]) {
right.put(i + 1, from);
from = i;
}
}
RMQ rmq = new RMQ(N);
for (Map.Entry<Integer, Integer> entry : left.entrySet()) {
from = entry.getKey();
int to = entry.getValue();
if (!right.containsKey(to)) continue;
int to2 = right.get(to);
int width = to2 - from + 1;
rmq.update(to, width);
}
long[] d = new long[N - 1];
for (int i = 0; i < N - 1; i++) {
d[i] = a[i + 1] - a[i];
}
int M = in.nextInt();
TreeSet<Integer> tmp = new TreeSet<>();
for (int i = 0; i < M; i++) {
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
long v = in.nextInt();
if (l > 0) {
long prev = d[l - 1];
d[l - 1] += v;
if (prev <= 0 && d[l - 1] > 0) {
// left merge
from = left.floorKey(l - 1);
int to = left.get(l);
left.remove(l);
rmq.update(l, 0);
left.put(from, to);
tmp.add(from);
}
if (prev < 0 && d[l - 1] >= 0) {
// right cut
Map.Entry<Integer, Integer> entry = right.floorEntry(l - 1);
from = entry.getKey();
int to = entry.getValue();
right.put(from, l - 1);
right.put(l, to);
rmq.update(from, 0);
tmp.add(left.floorKey(from));
tmp.add(left.floorKey(l));
}
}
if (r < N - 1) {
long prev = d[r];
d[r] -= v;
if (prev > 0 && d[r] <= 0) {
// left cut
Map.Entry<Integer, Integer> entry = left.floorEntry(r);
from = entry.getKey();
int to = entry.getValue();
left.put(from, r);
left.put(r + 1, to);
rmq.update(to, 0);
tmp.add(from);
tmp.add(r + 1);
}
if (prev >= 0 && d[r] < 0) {
// right merge
from = right.floorKey(r);
int to = right.get(r + 1);
right.remove(r + 1);
right.put(from, to);
rmq.update(from, 0);
tmp.add(left.floorKey(from));
}
}
for (int f : tmp) {
int k = left.get(f);
Integer to = right.get(k);
if (to==null) continue;
rmq.update(k, to - f + 1);
}
tmp.clear();
out.println(rmq.query(0, N + 1));
}
}
class RMQ {
private int N;
private long[] seg;
RMQ(int M) {
N = Integer.highestOneBit(M) * 2;
seg = new long[N * 2];
}
public void update(int k, long value) {
seg[k += N - 1] = value;
while (k > 0) {
k = (k - 1) / 2;
seg[k] = Math.max(seg[k * 2 + 1], seg[k * 2 + 2]);
}
}
//[a, b)
long query(int a, int b) {
return query(a, b, 0, 0, N);
}
long query(int a, int b, int k, int l, int r) {
if (r <= a || b <= l) return 0;
if (a <= l && r <= b) return seg[k];
long x = query(a, b, k * 2 + 1, l, (l + r) / 2);
long y = query(a, b, k * 2 + 2, (l + r) / 2, r);
return Math.max(x, y);
}
}
}
/**
* γγγγδΈγ―γγ³γγ¬γΌγγ§γγ
*/
public static void main(String[] args) throws Exception {
OutputStream outputStream = System.out;
FastScanner in = new FastScanner();
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
private static class FastScanner {
private final InputStream in = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int bufferLength = 0;
private boolean hasNextByte() {
if (ptr < bufferLength) {
return true;
} else {
ptr = 0;
try {
bufferLength = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (bufferLength <= 0) {
return false;
}
}
return true;
}
private int readByte() {
if (hasNextByte()) return buffer[ptr++];
else return -1;
}
private static boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
private void skipUnprintable() {
while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
}
boolean hasNext() {
skipUnprintable();
return hasNextByte();
}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
long nextLong() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while (true) {
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
} else if (b == -1 || !isPrintableChar(b)) {
return minus ? -n : n;
} else {
throw new NumberFormatException();
}
b = readByte();
}
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
double[] array = new double[n];
for (int i = 0; i < n; i++) {
array[i] = nextDouble();
}
return array;
}
double[][] nextDoubleMap(int n, int m) {
double[][] map = new double[n][];
for (int i = 0; i < n; i++) {
map[i] = nextDoubleArray(m);
}
return map;
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) array[i] = nextInt();
return array;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++) array[i] = nextLong();
return array;
}
public String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++) array[i] = next();
return array;
}
public char[][] nextCharMap(int n) {
char[][] array = new char[n][];
for (int i = 0; i < n; i++) array[i] = next().toCharArray();
return array;
}
public int[][] nextIntMap(int n, int m) {
int[][] map = new int[n][];
for (int i = 0; i < n; i++) {
map[i] = nextIntArray(m);
}
return map;
}
}
} | Java | ["5\n5 5 5 5 5\n3\n1 3 2\n2 2 1\n4 4 1"] | 2 seconds | ["2\n4\n5"] | NoteThe first sample is as follows:After addition of 2 cubes on the top of each towers from the first to the third, the number of cubes in the towers become equal to [7,β7,β7,β5,β5]. The hill with maximum width is [7,β5], thus the maximum width is 2.After addition of 1 cube on the second tower, the number of cubes in the towers become equal to [7,β8,β7,β5,β5]. The hill with maximum width is now [7,β8,β7,β5], thus the maximum width is 4.After addition of 1 cube on the fourth tower, the number of cubes in the towers become equal to [7,β8,β7,β6,β5]. The hill with maximum width is now [7,β8,β7,β6,β5], thus the maximum width is 5. | Java 8 | standard input | [] | a72fcdf5d159f1336f309cf4c6f73297 | The first line contain single integer n (1ββ€βnββ€β3Β·105)Β β the number of towers. The second line contain n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the number of cubes in each tower. The third line contain single integer m (1ββ€βmββ€β3Β·105)Β β the number of additions. The next m lines contain 3 integers each. The i-th of these lines contains integers li, ri and di (1ββ€βlββ€βrββ€βn, 1ββ€βdiββ€β109), that mean that Alyona puts di cubes on the tio of each of the towers from li to ri. | 2,500 | Print m lines. In i-th line print the maximum width of the hills after the i-th addition. | standard output | |
PASSED | ec263b3d7d47a95e6c10ac37a1c29c37 | train_004.jsonl | 1479918900 | Alyona has built n towers by putting small cubes some on the top of others. Each cube has size 1βΓβ1βΓβ1. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row.Sometimes Alyona chooses some segment towers, and put on the top of each tower several cubes. Formally, Alyouna chooses some segment of towers from li to ri and adds di cubes on the top of them.Let the sequence a1,βa2,β...,βan be the heights of the towers from left to right. Let's call as a segment of towers al,βalβ+β1,β...,βar a hill if the following condition holds: there is integer k (lββ€βkββ€βr) such that alβ<βalβ+β1β<βalβ+β2β<β...β<βakβ>βakβ+β1β>βakβ+β2β>β...β>βar.After each addition of di cubes on the top of the towers from li to ri, Alyona wants to know the maximum width among all hills. The width of a hill is the number of towers in it. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class AlyonaTowers {
int N = Integer.highestOneBit((int) 3e5) << 2;
int n;
long[] b;
Node[] node = new Node[N];
{
for (int i = 0; i < N; i++) node[i] = new Node(0, 0, 0);
}
void solve() {
n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = in.nextInt();
b = new long[n - 1];
for (int i = 0; i < n - 1; i++) b[i] = a[i + 1] - a[i];
if (n > 1) build(0, 0, n - 1);
int T = in.nextInt();
while (T-- > 0) {
int l = in.nextInt() - 1, r = in.nextInt(), d = in.nextInt();
if (n == 1) {
out.println(1);
} else {
if (l - 1 >= 0) update(l - 1, d);
if (r - 1 < n - 1) update(r - 1, -d);
out.println(node[0].m + 1);
}
}
}
void build(int i, int l, int r) {
if (l == r - 1) {
int x = b[l] == 0 ? 0 : 1;
node[i].l = node[i].m = node[i].r = x;
} else {
build(2 * i + 1, l, (l + r) / 2);
build(2 * i + 2, (l + r) / 2, r);
merge(i, l, r);
}
}
void merge(int i, int l, int r) {
int m = (l + r) / 2;
node[i].m = Math.max(node[2 * i + 1].m, node[2 * i + 2].m);
if (b[m - 1] == 0 || b[m] == 0 || sign(b[m - 1]) < sign(b[m])) {
node[i].l = node[2 * i + 1].l;
node[i].r = node[2 * i + 2].r;
} else {
node[i].m = Math.max(node[i].m, node[2 * i + 1].r + node[2 * i + 2].l);
if (node[2 * i + 1].m == m - l) {
node[i].l = node[2 * i + 1].l + node[2 * i + 2].l;
} else {
node[i].l = node[2 * i + 1].l;
}
if (node[2 * i + 2].m == r - m) {
node[i].r = node[2 * i + 1].r + node[2 * i + 2].r;
} else {
node[i].r = node[2 * i + 2].r;
}
}
}
void update(int i, int d) {
update(0, 0, n - 1, i, d);
}
void update(int k, int l, int r, int i, int d) {
if (l == r - 1) {
b[l] += d;
int x = b[l] == 0 ? 0 : 1;
node[k].l = node[k].m = node[k].r = x;
} else {
int m = (l + r) / 2;
if (i < m) update(2 * k + 1, l, (l + r) / 2, i, d);
else update(2 * k + 2, (l + r) / 2, r, i, d);
merge(k, l, r);
}
}
int sign(long x) {
return x > 0 ? 1 : x < 0 ? -1 : 0;
}
static class Node {
int l, m, r;
Node(int l, int m, int r) {
this.l = l;
this.m = m;
this.r = r;
}
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new AlyonaTowers().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["5\n5 5 5 5 5\n3\n1 3 2\n2 2 1\n4 4 1"] | 2 seconds | ["2\n4\n5"] | NoteThe first sample is as follows:After addition of 2 cubes on the top of each towers from the first to the third, the number of cubes in the towers become equal to [7,β7,β7,β5,β5]. The hill with maximum width is [7,β5], thus the maximum width is 2.After addition of 1 cube on the second tower, the number of cubes in the towers become equal to [7,β8,β7,β5,β5]. The hill with maximum width is now [7,β8,β7,β5], thus the maximum width is 4.After addition of 1 cube on the fourth tower, the number of cubes in the towers become equal to [7,β8,β7,β6,β5]. The hill with maximum width is now [7,β8,β7,β6,β5], thus the maximum width is 5. | Java 8 | standard input | [] | a72fcdf5d159f1336f309cf4c6f73297 | The first line contain single integer n (1ββ€βnββ€β3Β·105)Β β the number of towers. The second line contain n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the number of cubes in each tower. The third line contain single integer m (1ββ€βmββ€β3Β·105)Β β the number of additions. The next m lines contain 3 integers each. The i-th of these lines contains integers li, ri and di (1ββ€βlββ€βrββ€βn, 1ββ€βdiββ€β109), that mean that Alyona puts di cubes on the tio of each of the towers from li to ri. | 2,500 | Print m lines. In i-th line print the maximum width of the hills after the i-th addition. | standard output | |
PASSED | 1a13c6d96cecc89ee51fdcbe1f0a55e9 | train_004.jsonl | 1479918900 | Alyona has built n towers by putting small cubes some on the top of others. Each cube has size 1βΓβ1βΓβ1. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row.Sometimes Alyona chooses some segment towers, and put on the top of each tower several cubes. Formally, Alyouna chooses some segment of towers from li to ri and adds di cubes on the top of them.Let the sequence a1,βa2,β...,βan be the heights of the towers from left to right. Let's call as a segment of towers al,βalβ+β1,β...,βar a hill if the following condition holds: there is integer k (lββ€βkββ€βr) such that alβ<βalβ+β1β<βalβ+β2β<β...β<βakβ>βakβ+β1β>βakβ+β2β>β...β>βar.After each addition of di cubes on the top of the towers from li to ri, Alyona wants to know the maximum width among all hills. The width of a hill is the number of towers in it. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF740E {
static Random rand = new Random();
static class Skip<K,E> {
static class Entry<K,E> {
K k;
E e;
Entry(K k, E e) {
this.k = k;
this.e = e;
}
}
static class Item<K,E> {
Item<K,E> north, south, west, east;
Entry<K,E> ent;
};
Item<K,E> root = new Item<>();
Comparator<K> comp;
Skip(Comparator<K> comp) {
this.comp = comp;
}
private Item<K,E> search(K k) {
Item<K,E> x = root;
while (x.south != null) {
x = x.south;
while (x.east != null && comp.compare(x.east.ent.k, k) <= 0)
x = x.east;
}
return x;
}
K first() {
Item<K,E> x = root;
while (x.south != null)
x = x.south;
x = x.east;
return x == null || x.ent == null ? null : x.ent.k;
}
K floor(K k) {
Item<K,E> x = search(k);
return x.ent == null ? null : x.ent.k;
}
K lower(K k) {
Item<K,E> x = search(k);
if (x.ent == null || comp.compare(x.ent.k, k) < 0)
return x.ent == null ? null : x.ent.k;
x = x.west;
return x == null || x.ent == null ? null : x.ent.k;
}
K higher(K k) {
Item<K,E> x = search(k);
x = x.east;
return x == null || x.ent == null ? null : x.ent.k;
}
E get(K k) {
Item<K,E> x = search(k);
Entry<K,E> ent = x.ent;
return ent == null || comp.compare(ent.k, k) != 0 ? null : ent.e;
}
private void raise(Item<K,E> x) {
if (x == root) {
root = new Item<>();
root.south = x;
x.north = root;
}
}
private Item<K,E> insertAfterAbove(Item<K,E> west, Item<K,E> south, Entry<K,E> ent) {
Item<K,E> x = new Item<>();
if (west != null) {
if (west.east != null) {
x.east = west.east;
west.east.west = x;
}
x.west = west;
west.east = x;
}
if (south != null) {
if (south.north != null) {
x.north = south.north;
south.north.south = x;
}
x.south = south;
south.north = x;
}
x.ent = ent;
return x;
}
void put(K k, E e) {
Item<K,E> x = search(k);
Entry<K,E> ent = x.ent;
if (ent != null && comp.compare(ent.k, k) == 0) {
ent.e = e;
return;
}
ent = new Entry<>(k, e);
raise(x);
Item<K,E> y = insertAfterAbove(x, null, ent);
while (rand.nextInt(2) == 0) {
while (x.north == null)
x = x.west;
x = x.north;
raise(x);
y = insertAfterAbove(x, y, ent);
}
}
E remove(K k) {
Item<K,E> x = search(k), y;
Entry<K,E> ent = x.ent;
if (ent == null || comp.compare(ent.k, k) != 0)
return null;
while (x != null) {
y = x.north;
if (x.west != null)
x.west.east = x.east;
if (x.east != null)
x.east.west = x.west;
//free(x);
x = y;
}
E e = ent.e;
//free(ent);
return e;
}
};
static long[] aa;
static class H {
int i, j, k; // [i, j) up [j, k) down
H(int i, int j, int k) {
this.i = i;
this.j = j;
this.k = k;
}
}
//static TreeSet<H> xx = new TreeSet<>((p, q) -> p.i - q.i);
static Skip<H,H> xx = new Skip<>((p, q) -> p.i - q.i);
static TreeMap<Integer, Integer> ww = new TreeMap<>();
static void add(int i, int j, int k) {
if (i <= j && j <= k && i < k) {
H h = new H(i, j, k);
//xx.add(h);
xx.put(h, h);
int key = k - i;
int cnt = ww.getOrDefault(key, 0);
ww.put(key, cnt + 1);
}
}
static void remove(H h) {
xx.remove(h);
int key = h.k - h.i;
int cnt = ww.getOrDefault(key, 0);
if (cnt == 1)
ww.remove(key);
else
ww.put(key, cnt - 1);
}
static void init() {
int n = aa.length;
for (int i = 0, j, k; i < n; ) {
j = i;
while (j < n && aa[j] > 0)
j++;
k = j;
while (k < n && aa[k] < 0)
k++;
if (i < k) {
add(i, j, k);
i = k;
} else
i++;
}
}
static void join(int i) {
H h = xx.floor(new H(i, i, i));
H l = xx.lower(h);
H r = xx.higher(h);
boolean lh = l != null && l.k == h.i && (l.j == l.k || h.i == h.j);
boolean hr = r != null && h.k == r.i && (h.j == h.k || r.i == r.j);
if (lh && hr) {
remove(l);
remove(h);
remove(r);
add(l.i, h.i == h.j ? l.j : r.j, r.k);
} else if (lh) {
remove(l);
remove(h);
add(l.i, h.i == h.j ? l.j : h.j, h.k);
} else if (hr) {
remove(h);
remove(r);
add(h.i, r.i == r.j ? h.j : r.j, r.k);
}
}
static void update(int i, int d) {
long a = aa[i];
long b = aa[i] += d; // d != 0
if (a == 0) {
add(i, b > 0 ? i + 1 : i, i + 1);
join(i);
} else if (b == 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
if (a > 0) {
add(h.i, i, i);
add(i + 1, h.j, h.k);
} else {
add(h.i, h.j, i);
add(i + 1, i + 1, h.k);
}
} else if (a > 0 && b < 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
add(h.i, i, i + 1);
add(i + 1, h.j, h.k);
join(i);
} else if (a < 0 && b > 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
add(h.i, h.j, i);
add(i, i + 1, h.k);
join(i);
}
}
static int query() {
return ww.isEmpty() ? 1 : ww.lastKey() + 1;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
aa = new long[n - 1];
int a_ = Integer.parseInt(st.nextToken());
for (int i = 0; i < n - 1; i++) {
int a = Integer.parseInt(st.nextToken());
aa[i] = a - a_;
a_ = a;
}
init();
int m = Integer.parseInt(br.readLine());
PrintWriter pw = new PrintWriter(System.out);
while (m-- > 0) {
st = new StringTokenizer(br.readLine());
int l = Integer.parseInt(st.nextToken()) - 1;
int r = Integer.parseInt(st.nextToken()) - 1;
int d = Integer.parseInt(st.nextToken());
if (l > 0)
update(l - 1, d);
if (r < n - 1)
update(r, -d);
pw.println(query());
}
pw.close();
}
}
| Java | ["5\n5 5 5 5 5\n3\n1 3 2\n2 2 1\n4 4 1"] | 2 seconds | ["2\n4\n5"] | NoteThe first sample is as follows:After addition of 2 cubes on the top of each towers from the first to the third, the number of cubes in the towers become equal to [7,β7,β7,β5,β5]. The hill with maximum width is [7,β5], thus the maximum width is 2.After addition of 1 cube on the second tower, the number of cubes in the towers become equal to [7,β8,β7,β5,β5]. The hill with maximum width is now [7,β8,β7,β5], thus the maximum width is 4.After addition of 1 cube on the fourth tower, the number of cubes in the towers become equal to [7,β8,β7,β6,β5]. The hill with maximum width is now [7,β8,β7,β6,β5], thus the maximum width is 5. | Java 8 | standard input | [] | a72fcdf5d159f1336f309cf4c6f73297 | The first line contain single integer n (1ββ€βnββ€β3Β·105)Β β the number of towers. The second line contain n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the number of cubes in each tower. The third line contain single integer m (1ββ€βmββ€β3Β·105)Β β the number of additions. The next m lines contain 3 integers each. The i-th of these lines contains integers li, ri and di (1ββ€βlββ€βrββ€βn, 1ββ€βdiββ€β109), that mean that Alyona puts di cubes on the tio of each of the towers from li to ri. | 2,500 | Print m lines. In i-th line print the maximum width of the hills after the i-th addition. | standard output | |
PASSED | 3534cbac98b46b7f0c0ce72c9ba94a2e | train_004.jsonl | 1479918900 | Alyona has built n towers by putting small cubes some on the top of others. Each cube has size 1βΓβ1βΓβ1. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row.Sometimes Alyona chooses some segment towers, and put on the top of each tower several cubes. Formally, Alyouna chooses some segment of towers from li to ri and adds di cubes on the top of them.Let the sequence a1,βa2,β...,βan be the heights of the towers from left to right. Let's call as a segment of towers al,βalβ+β1,β...,βar a hill if the following condition holds: there is integer k (lββ€βkββ€βr) such that alβ<βalβ+β1β<βalβ+β2β<β...β<βakβ>βakβ+β1β>βakβ+β2β>β...β>βar.After each addition of di cubes on the top of the towers from li to ri, Alyona wants to know the maximum width among all hills. The width of a hill is the number of towers in it. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF740E {
static Random rand = new Random();
static class Skip<K,V> {
Comparator<K> comp;
static class Node<K,V> {
K k;
V v;
Node<K,V>[] next;
Node(int r, K k, V v) {
next = new Node[r]; // unchecked
this.k = k;
this.v = v;
}
}
Node<K,V> header;
Node<K,V>[] update;
int l, m;
Skip(int n, Comparator<K> comp) {
m = 1;
while (1 << m + m < n) // n <= power(1/p, m) for p = 1/4
m++;
header = new Node<>(m, null, null);
update = new Node[m]; // unchecked
l = 1;
this.comp = comp;
}
private Node<K,V> search(K k) {
Node<K,V> x = header;
for (int i = l - 1; i >= 0; i--)
while (x.next[i] != null && comp.compare(x.next[i].k, k) < 0)
x = x.next[i];
return x;
}
private Node<K,V> search_(K k) {
Node<K,V> x = header;
for (int i = l - 1; i >= 0; i--) {
while (x.next[i] != null && comp.compare(x.next[i].k, k) < 0)
x = x.next[i];
update[i] = x;
}
return x;
}
K first() {
Node<K,V> x = header;
x = x.next[0];
return x == null ? null : x.k;
}
K last() {
Node<K,V> x = header;
for (int i = l - 1; i >= 0; i--)
while (x.next[i] != null)
x = x.next[i];
x = x.next[0];
return x == null ? null : x.k;
}
K lower(K k) {
Node<K,V> x = search(k);
return x.k;
}
K floor(K k) {
Node<K,V> x = search(k), y = x.next[0];
if (y != null && comp.compare(y.k, k) == 0)
return y.k;
return x.k;
}
K higher(K k) {
Node<K,V> x = search(k);
x = x.next[0];
if (x != null && comp.compare(x.k, k) == 0)
x = x.next[0];
return x == null ? null : x.k;
}
V getOrDefault(K k, V v) {
Node<K,V> x = search(k);
x = x.next[0];
if (x != null && comp.compare(x.k, k) == 0)
return x.v;
return v;
}
void put(K k, V v) {
Node<K,V> x = search_(k);
x = x.next[0];
if (x != null && comp.compare(x.k, k) == 0) {
x.v = v;
return;
}
int r = 1;
while (r < m && rand.nextInt(4) == 0) // p = 1/4
r++;
if (r > l) {
for (int i = l; i < r; i++)
update[i] = header;
l = r;
}
x = new Node<>(r, k, v);
for (int i = 0; i < r; i++) {
x.next[i] = update[i].next[i];
update[i].next[i] = x;
}
}
V remove(K k) {
Node<K,V> x = search_(k);
x = x.next[0];
if (x != null && comp.compare(x.k, k) == 0) {
for (int i = 0; i < l; i++) {
if (update[i].next[i] != x)
break;
update[i].next[i] = x.next[i];
}
while (l > 1 && header.next[l - 1] == null)
l--;
V v = x.v;
// free(x);
return v;
}
return null;
}
};
static long[] aa;
static class H {
int i, j, k; // [i, j) up [j, k) down
H(int i, int j, int k) {
this.i = i;
this.j = j;
this.k = k;
}
}
//static TreeSet<H> xx = new TreeSet<>((p, q) -> p.i - q.i);
static Skip<H,H> xx;
static TreeMap<Integer, Integer> ww = new TreeMap<>();
//static Skip<Integer,Integer> ww = new Skip<>((p, q) -> p - q);
static void add(int i, int j, int k) {
if (i <= j && j <= k && i < k) {
H h = new H(i, j, k);
//xx.add(h);
xx.put(h, h);
int key = k - i;
int cnt = ww.getOrDefault(key, 0);
ww.put(key, cnt + 1);
}
}
static void remove(H h) {
xx.remove(h);
int key = h.k - h.i;
int cnt = ww.getOrDefault(key, 0);
if (cnt == 1)
ww.remove(key);
else
ww.put(key, cnt - 1);
}
static void init() {
int n = aa.length;
for (int i = 0, j, k; i < n; ) {
j = i;
while (j < n && aa[j] > 0)
j++;
k = j;
while (k < n && aa[k] < 0)
k++;
if (i < k) {
add(i, j, k);
i = k;
} else
i++;
}
}
static void join(int i) {
H h = xx.floor(new H(i, i, i));
H l = xx.lower(h);
H r = xx.higher(h);
boolean lh = l != null && l.k == h.i && (l.j == l.k || h.i == h.j);
boolean hr = r != null && h.k == r.i && (h.j == h.k || r.i == r.j);
if (lh && hr) {
remove(l);
remove(h);
remove(r);
add(l.i, h.i == h.j ? l.j : r.j, r.k);
} else if (lh) {
remove(l);
remove(h);
add(l.i, h.i == h.j ? l.j : h.j, h.k);
} else if (hr) {
remove(h);
remove(r);
add(h.i, r.i == r.j ? h.j : r.j, r.k);
}
}
static void update(int i, int d) {
long a = aa[i];
long b = aa[i] += d; // d != 0
if (a == 0) {
add(i, b > 0 ? i + 1 : i, i + 1);
join(i);
} else if (b == 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
if (a > 0) {
add(h.i, i, i);
add(i + 1, h.j, h.k);
} else {
add(h.i, h.j, i);
add(i + 1, i + 1, h.k);
}
} else if (a > 0 && b < 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
add(h.i, i, i + 1);
add(i + 1, h.j, h.k);
join(i);
} else if (a < 0 && b > 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
add(h.i, h.j, i);
add(i, i + 1, h.k);
join(i);
}
}
static int query() {
return ww.isEmpty() ? 1 : ww.lastKey() + 1;
//Integer l = ww.last();
//return l == null ? 1 : l + 1;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
aa = new long[n - 1];
int a_ = Integer.parseInt(st.nextToken());
for (int i = 0; i < n - 1; i++) {
int a = Integer.parseInt(st.nextToken());
aa[i] = a - a_;
a_ = a;
}
xx = new Skip<>(n, (p, q) -> p.i - q.i);
init();
int m = Integer.parseInt(br.readLine());
PrintWriter pw = new PrintWriter(System.out);
while (m-- > 0) {
st = new StringTokenizer(br.readLine());
int l = Integer.parseInt(st.nextToken()) - 1;
int r = Integer.parseInt(st.nextToken()) - 1;
int d = Integer.parseInt(st.nextToken());
if (l > 0)
update(l - 1, d);
if (r < n - 1)
update(r, -d);
pw.println(query());
}
pw.close();
}
}
| Java | ["5\n5 5 5 5 5\n3\n1 3 2\n2 2 1\n4 4 1"] | 2 seconds | ["2\n4\n5"] | NoteThe first sample is as follows:After addition of 2 cubes on the top of each towers from the first to the third, the number of cubes in the towers become equal to [7,β7,β7,β5,β5]. The hill with maximum width is [7,β5], thus the maximum width is 2.After addition of 1 cube on the second tower, the number of cubes in the towers become equal to [7,β8,β7,β5,β5]. The hill with maximum width is now [7,β8,β7,β5], thus the maximum width is 4.After addition of 1 cube on the fourth tower, the number of cubes in the towers become equal to [7,β8,β7,β6,β5]. The hill with maximum width is now [7,β8,β7,β6,β5], thus the maximum width is 5. | Java 8 | standard input | [] | a72fcdf5d159f1336f309cf4c6f73297 | The first line contain single integer n (1ββ€βnββ€β3Β·105)Β β the number of towers. The second line contain n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the number of cubes in each tower. The third line contain single integer m (1ββ€βmββ€β3Β·105)Β β the number of additions. The next m lines contain 3 integers each. The i-th of these lines contains integers li, ri and di (1ββ€βlββ€βrββ€βn, 1ββ€βdiββ€β109), that mean that Alyona puts di cubes on the tio of each of the towers from li to ri. | 2,500 | Print m lines. In i-th line print the maximum width of the hills after the i-th addition. | standard output | |
PASSED | 7431c6129cda3ca6e82ed08b00e03f50 | train_004.jsonl | 1479918900 | Alyona has built n towers by putting small cubes some on the top of others. Each cube has size 1βΓβ1βΓβ1. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row.Sometimes Alyona chooses some segment towers, and put on the top of each tower several cubes. Formally, Alyouna chooses some segment of towers from li to ri and adds di cubes on the top of them.Let the sequence a1,βa2,β...,βan be the heights of the towers from left to right. Let's call as a segment of towers al,βalβ+β1,β...,βar a hill if the following condition holds: there is integer k (lββ€βkββ€βr) such that alβ<βalβ+β1β<βalβ+β2β<β...β<βakβ>βakβ+β1β>βakβ+β2β>β...β>βar.After each addition of di cubes on the top of the towers from li to ri, Alyona wants to know the maximum width among all hills. The width of a hill is the number of towers in it. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF740E {
static long[] aa;
static class H implements Comparable<H> {
int i, j, k; // [i, j) up [j, k) down
H(int i, int j, int k) {
this.i = i;
this.j = j;
this.k = k;
}
@Override public int compareTo(H h) {
return k - i != h.k - h.i ? (k - i) - (h.k - h.i) : i - h.i;
}
}
static TreeSet<H> xx = new TreeSet<>((p, q) -> p.i - q.i);
static TreeMap<Integer, Integer> ww = new TreeMap<>();
static void add(int i, int j, int k) {
if (i <= j && j <= k && i < k) {
H h = new H(i, j, k);
xx.add(h);
int key = k - i;
int cnt = ww.getOrDefault(key, 0);
ww.put(key, cnt + 1);
}
}
static void remove(H h) {
xx.remove(h);
int key = h.k - h.i;
int cnt = ww.getOrDefault(key, 0);
if (cnt == 1)
ww.remove(key);
else
ww.put(key, cnt - 1);
}
static void init() {
int n = aa.length;
for (int i = 0, j, k; i < n; ) {
j = i;
while (j < n && aa[j] > 0)
j++;
k = j;
while (k < n && aa[k] < 0)
k++;
if (i < k) {
add(i, j, k);
i = k;
} else
i++;
}
}
static void join(int i) {
H h = xx.floor(new H(i, i, i));
H l = xx.lower(h);
H r = xx.higher(h);
boolean lh = l != null && l.k == h.i && (l.j == l.k || h.i == h.j);
boolean hr = r != null && h.k == r.i && (h.j == h.k || r.i == r.j);
if (lh && hr) {
remove(l);
remove(h);
remove(r);
add(l.i, h.i == h.j ? l.j : r.j, r.k);
} else if (lh) {
remove(l);
remove(h);
add(l.i, h.i == h.j ? l.j : h.j, h.k);
} else if (hr) {
remove(h);
remove(r);
add(h.i, r.i == r.j ? h.j : r.j, r.k);
}
}
static void update(int i, int d) {
long a = aa[i];
long b = aa[i] += d; // d != 0
if (a == 0) {
add(i, b > 0 ? i + 1 : i, i + 1);
join(i);
} else if (b == 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
if (a > 0) {
add(h.i, i, i);
add(i + 1, h.j, h.k);
} else {
add(h.i, h.j, i);
add(i + 1, i + 1, h.k);
}
} else if (a > 0 && b < 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
add(h.i, i, i + 1);
add(i + 1, h.j, h.k);
join(i);
} else if (a < 0 && b > 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
add(h.i, h.j, i);
add(i, i + 1, h.k);
join(i);
}
}
static int query() {
return ww.isEmpty() ? 1 : ww.lastKey() + 1;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
aa = new long[n - 1];
int a_ = Integer.parseInt(st.nextToken());
for (int i = 0; i < n - 1; i++) {
int a = Integer.parseInt(st.nextToken());
aa[i] = a - a_;
a_ = a;
}
init();
int m = Integer.parseInt(br.readLine());
PrintWriter pw = new PrintWriter(System.out);
while (m-- > 0) {
st = new StringTokenizer(br.readLine());
int l = Integer.parseInt(st.nextToken()) - 1;
int r = Integer.parseInt(st.nextToken()) - 1;
int d = Integer.parseInt(st.nextToken());
if (l > 0)
update(l - 1, d);
if (r < n - 1)
update(r, -d);
pw.println(query());
}
pw.close();
}
}
| Java | ["5\n5 5 5 5 5\n3\n1 3 2\n2 2 1\n4 4 1"] | 2 seconds | ["2\n4\n5"] | NoteThe first sample is as follows:After addition of 2 cubes on the top of each towers from the first to the third, the number of cubes in the towers become equal to [7,β7,β7,β5,β5]. The hill with maximum width is [7,β5], thus the maximum width is 2.After addition of 1 cube on the second tower, the number of cubes in the towers become equal to [7,β8,β7,β5,β5]. The hill with maximum width is now [7,β8,β7,β5], thus the maximum width is 4.After addition of 1 cube on the fourth tower, the number of cubes in the towers become equal to [7,β8,β7,β6,β5]. The hill with maximum width is now [7,β8,β7,β6,β5], thus the maximum width is 5. | Java 8 | standard input | [] | a72fcdf5d159f1336f309cf4c6f73297 | The first line contain single integer n (1ββ€βnββ€β3Β·105)Β β the number of towers. The second line contain n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the number of cubes in each tower. The third line contain single integer m (1ββ€βmββ€β3Β·105)Β β the number of additions. The next m lines contain 3 integers each. The i-th of these lines contains integers li, ri and di (1ββ€βlββ€βrββ€βn, 1ββ€βdiββ€β109), that mean that Alyona puts di cubes on the tio of each of the towers from li to ri. | 2,500 | Print m lines. In i-th line print the maximum width of the hills after the i-th addition. | standard output | |
PASSED | 588069912d217e8b3136d460af6947e0 | train_004.jsonl | 1479918900 | Alyona has built n towers by putting small cubes some on the top of others. Each cube has size 1βΓβ1βΓβ1. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row.Sometimes Alyona chooses some segment towers, and put on the top of each tower several cubes. Formally, Alyouna chooses some segment of towers from li to ri and adds di cubes on the top of them.Let the sequence a1,βa2,β...,βan be the heights of the towers from left to right. Let's call as a segment of towers al,βalβ+β1,β...,βar a hill if the following condition holds: there is integer k (lββ€βkββ€βr) such that alβ<βalβ+β1β<βalβ+β2β<β...β<βakβ>βakβ+β1β>βakβ+β2β>β...β>βar.After each addition of di cubes on the top of the towers from li to ri, Alyona wants to know the maximum width among all hills. The width of a hill is the number of towers in it. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF740E {
static Random rand = new Random();
static class Skip<K,V> {
Comparator<K> comp;
static class Node<K,V> {
K k;
V v;
Node<K,V>[] next;
Node(int r, K k, V v) {
next = new Node[r]; // unchecked
this.k = k;
this.v = v;
}
}
Node<K,V> header;
Node<K,V>[] update;
int l, m;
Skip(int n, Comparator<K> comp) {
m = 1;
while (1 << m + m < n) // n <= power(1/p, m) for p = 1/4
m++;
header = new Node<>(m, null, null);
update = new Node[m]; // unchecked
l = 1;
this.comp = comp;
}
private Node<K,V> search(K k) {
Node<K,V> x = header;
for (int i = l - 1; i >= 0; i--)
while (x.next[i] != null && comp.compare(x.next[i].k, k) < 0)
x = x.next[i];
return x;
}
private Node<K,V> search_(K k) {
Node<K,V> x = header;
for (int i = l - 1; i >= 0; i--) {
while (x.next[i] != null && comp.compare(x.next[i].k, k) < 0)
x = x.next[i];
update[i] = x;
}
return x;
}
K first() {
Node<K,V> x = header;
x = x.next[0];
return x == null ? null : x.k;
}
K last() {
Node<K,V> x = header;
for (int i = l - 1; i >= 0; i--)
while (x.next[i] != null)
x = x.next[i];
return x.k;
}
K lower(K k) {
Node<K,V> x = search(k);
return x.k;
}
K floor(K k) {
Node<K,V> x = search(k), y = x.next[0];
if (y != null && comp.compare(y.k, k) == 0)
return y.k;
return x.k;
}
K higher(K k) {
Node<K,V> x = search(k);
x = x.next[0];
if (x != null && comp.compare(x.k, k) == 0)
x = x.next[0];
return x == null ? null : x.k;
}
V getOrDefault(K k, V v) {
Node<K,V> x = search(k);
x = x.next[0];
if (x != null && comp.compare(x.k, k) == 0)
return x.v;
return v;
}
void put(K k, V v) {
Node<K,V> x = search_(k);
x = x.next[0];
if (x != null && comp.compare(x.k, k) == 0) {
x.v = v;
return;
}
int r = 1;
while (r < m && rand.nextInt(4) == 0) // p = 1/4
r++;
if (r > l) {
for (int i = l; i < r; i++)
update[i] = header;
l = r;
}
x = new Node<>(r, k, v);
for (int i = 0; i < r; i++) {
x.next[i] = update[i].next[i];
update[i].next[i] = x;
}
}
V remove(K k) {
Node<K,V> x = search_(k);
x = x.next[0];
if (x != null && comp.compare(x.k, k) == 0) {
for (int i = 0; i < l; i++) {
if (update[i].next[i] != x)
break;
update[i].next[i] = x.next[i];
}
while (l > 1 && header.next[l - 1] == null)
l--;
V v = x.v;
// free(x);
return v;
}
return null;
}
};
static long[] aa;
static class H {
int i, j, k; // [i, j) up [j, k) down
H(int i, int j, int k) {
this.i = i;
this.j = j;
this.k = k;
}
}
//static TreeSet<H> xx = new TreeSet<>((p, q) -> p.i - q.i);
static Skip<H,H> xx;
//static TreeMap<Integer, Integer> ww = new TreeMap<>();
static Skip<Integer,Integer> ww;
static void add(int i, int j, int k) {
if (i <= j && j <= k && i < k) {
H h = new H(i, j, k);
//xx.add(h);
xx.put(h, h);
int key = k - i;
int cnt = ww.getOrDefault(key, 0);
ww.put(key, cnt + 1);
}
}
static void remove(H h) {
xx.remove(h);
int key = h.k - h.i;
int cnt = ww.getOrDefault(key, 0);
if (cnt == 1)
ww.remove(key);
else
ww.put(key, cnt - 1);
}
static void init() {
int n = aa.length;
for (int i = 0, j, k; i < n; ) {
j = i;
while (j < n && aa[j] > 0)
j++;
k = j;
while (k < n && aa[k] < 0)
k++;
if (i < k) {
add(i, j, k);
i = k;
} else
i++;
}
}
static void join(int i) {
H h = xx.floor(new H(i, i, i));
H l = xx.lower(h);
H r = xx.higher(h);
boolean lh = l != null && l.k == h.i && (l.j == l.k || h.i == h.j);
boolean hr = r != null && h.k == r.i && (h.j == h.k || r.i == r.j);
if (lh && hr) {
remove(l);
remove(h);
remove(r);
add(l.i, h.i == h.j ? l.j : r.j, r.k);
} else if (lh) {
remove(l);
remove(h);
add(l.i, h.i == h.j ? l.j : h.j, h.k);
} else if (hr) {
remove(h);
remove(r);
add(h.i, r.i == r.j ? h.j : r.j, r.k);
}
}
static void update(int i, int d) {
long a = aa[i];
long b = aa[i] += d; // d != 0
if (a == 0) {
add(i, b > 0 ? i + 1 : i, i + 1);
join(i);
} else if (b == 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
if (a > 0) {
add(h.i, i, i);
add(i + 1, h.j, h.k);
} else {
add(h.i, h.j, i);
add(i + 1, i + 1, h.k);
}
} else if (a > 0 && b < 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
add(h.i, i, i + 1);
add(i + 1, h.j, h.k);
join(i);
} else if (a < 0 && b > 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
add(h.i, h.j, i);
add(i, i + 1, h.k);
join(i);
}
}
static int query() {
//return ww.isEmpty() ? 1 : ww.lastKey() + 1;
Integer l = ww.last();
return l == null ? 1 : l + 1;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
aa = new long[n - 1];
int a_ = Integer.parseInt(st.nextToken());
for (int i = 0; i < n - 1; i++) {
int a = Integer.parseInt(st.nextToken());
aa[i] = a - a_;
a_ = a;
}
xx = new Skip<>(n, (p, q) -> p.i - q.i);
ww = new Skip<>((int) Math.sqrt(n), (p, q) -> p - q);
init();
int m = Integer.parseInt(br.readLine());
PrintWriter pw = new PrintWriter(System.out);
while (m-- > 0) {
st = new StringTokenizer(br.readLine());
int l = Integer.parseInt(st.nextToken()) - 1;
int r = Integer.parseInt(st.nextToken()) - 1;
int d = Integer.parseInt(st.nextToken());
if (l > 0)
update(l - 1, d);
if (r < n - 1)
update(r, -d);
pw.println(query());
}
pw.close();
}
}
| Java | ["5\n5 5 5 5 5\n3\n1 3 2\n2 2 1\n4 4 1"] | 2 seconds | ["2\n4\n5"] | NoteThe first sample is as follows:After addition of 2 cubes on the top of each towers from the first to the third, the number of cubes in the towers become equal to [7,β7,β7,β5,β5]. The hill with maximum width is [7,β5], thus the maximum width is 2.After addition of 1 cube on the second tower, the number of cubes in the towers become equal to [7,β8,β7,β5,β5]. The hill with maximum width is now [7,β8,β7,β5], thus the maximum width is 4.After addition of 1 cube on the fourth tower, the number of cubes in the towers become equal to [7,β8,β7,β6,β5]. The hill with maximum width is now [7,β8,β7,β6,β5], thus the maximum width is 5. | Java 8 | standard input | [] | a72fcdf5d159f1336f309cf4c6f73297 | The first line contain single integer n (1ββ€βnββ€β3Β·105)Β β the number of towers. The second line contain n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the number of cubes in each tower. The third line contain single integer m (1ββ€βmββ€β3Β·105)Β β the number of additions. The next m lines contain 3 integers each. The i-th of these lines contains integers li, ri and di (1ββ€βlββ€βrββ€βn, 1ββ€βdiββ€β109), that mean that Alyona puts di cubes on the tio of each of the towers from li to ri. | 2,500 | Print m lines. In i-th line print the maximum width of the hills after the i-th addition. | standard output | |
PASSED | 1df77dac6ba8abc59b063ea5eb5e975c | train_004.jsonl | 1479918900 | Alyona has built n towers by putting small cubes some on the top of others. Each cube has size 1βΓβ1βΓβ1. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row.Sometimes Alyona chooses some segment towers, and put on the top of each tower several cubes. Formally, Alyouna chooses some segment of towers from li to ri and adds di cubes on the top of them.Let the sequence a1,βa2,β...,βan be the heights of the towers from left to right. Let's call as a segment of towers al,βalβ+β1,β...,βar a hill if the following condition holds: there is integer k (lββ€βkββ€βr) such that alβ<βalβ+β1β<βalβ+β2β<β...β<βakβ>βakβ+β1β>βakβ+β2β>β...β>βar.After each addition of di cubes on the top of the towers from li to ri, Alyona wants to know the maximum width among all hills. The width of a hill is the number of towers in it. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF740E {
static Random rand = new Random();
static class Skip<K,V> {
Comparator<K> comp;
static class Node<K,V> {
K k;
V v;
Node<K,V>[] next;
Node(int r, K k, V v) {
next = new Node[r]; // unchecked
this.k = k;
this.v = v;
}
}
Node<K,V> header;
Node<K,V>[] update;
int l, m;
Skip(int n, Comparator<K> comp) {
m = 1;
while (1 << m + m < n) // n <= power(1/p, m) for p = 1/4
m++;
header = new Node<>(m, null, null);
update = new Node[m]; // unchecked
l = 1;
this.comp = comp;
}
private Node<K,V> search(K k) {
Node<K,V> x = header;
for (int i = l - 1; i >= 0; i--)
while (x.next[i] != null && comp.compare(x.next[i].k, k) < 0)
x = x.next[i];
return x;
}
private Node<K,V> search_(K k) {
Node<K,V> x = header;
for (int i = l - 1; i >= 0; i--) {
while (x.next[i] != null && comp.compare(x.next[i].k, k) < 0)
x = x.next[i];
update[i] = x;
}
return x;
}
K first() {
Node<K,V> x = header;
x = x.next[0];
return x == null ? null : x.k;
}
K last() {
Node<K,V> x = header;
for (int i = l - 1; i >= 0; i--)
while (x.next[i] != null)
x = x.next[i];
return x.k;
}
K lower(K k) {
Node<K,V> x = search(k);
return x.k;
}
K floor(K k) {
Node<K,V> x = search(k), y = x.next[0];
if (y != null && comp.compare(y.k, k) == 0)
return y.k;
return x.k;
}
K higher(K k) {
Node<K,V> x = search(k);
x = x.next[0];
if (x != null && comp.compare(x.k, k) == 0)
x = x.next[0];
return x == null ? null : x.k;
}
V getOrDefault(K k, V v) {
Node<K,V> x = search(k);
x = x.next[0];
if (x != null && comp.compare(x.k, k) == 0)
return x.v;
return v;
}
void put(K k, V v) {
Node<K,V> x = search_(k);
x = x.next[0];
if (x != null && comp.compare(x.k, k) == 0) {
x.v = v;
return;
}
int r = 1;
while (r < m && rand.nextInt(4) == 0) // p = 1/4
r++;
if (r > l) {
for (int i = l; i < r; i++)
update[i] = header;
l = r;
}
x = new Node<>(r, k, v);
for (int i = 0; i < r; i++) {
x.next[i] = update[i].next[i];
update[i].next[i] = x;
}
}
V remove(K k) {
Node<K,V> x = search_(k);
x = x.next[0];
if (x != null && comp.compare(x.k, k) == 0) {
for (int i = 0; i < l; i++) {
if (update[i].next[i] != x)
break;
update[i].next[i] = x.next[i];
}
while (l > 1 && header.next[l - 1] == null)
l--;
V v = x.v;
// free(x);
return v;
}
return null;
}
};
static long[] aa;
static class H {
int i, j, k; // [i, j) up [j, k) down
H(int i, int j, int k) {
this.i = i;
this.j = j;
this.k = k;
}
}
//static TreeSet<H> xx = new TreeSet<>((p, q) -> p.i - q.i);
static Skip<H,H> xx;
//static TreeMap<Integer, Integer> ww = new TreeMap<>();
static Skip<Integer,Integer> ww;
static void add(int i, int j, int k) {
if (i <= j && j <= k && i < k) {
H h = new H(i, j, k);
//xx.add(h);
xx.put(h, h);
int key = k - i;
int cnt = ww.getOrDefault(key, 0);
ww.put(key, cnt + 1);
}
}
static void remove(H h) {
xx.remove(h);
int key = h.k - h.i;
int cnt = ww.getOrDefault(key, 0);
if (cnt == 1)
ww.remove(key);
else
ww.put(key, cnt - 1);
}
static void init() {
int n = aa.length;
for (int i = 0, j, k; i < n; ) {
j = i;
while (j < n && aa[j] > 0)
j++;
k = j;
while (k < n && aa[k] < 0)
k++;
if (i < k) {
add(i, j, k);
i = k;
} else
i++;
}
}
static void join(int i) {
H h = xx.floor(new H(i, i, i));
H l = xx.lower(h);
H r = xx.higher(h);
boolean lh = l != null && l.k == h.i && (l.j == l.k || h.i == h.j);
boolean hr = r != null && h.k == r.i && (h.j == h.k || r.i == r.j);
if (lh && hr) {
remove(l);
remove(h);
remove(r);
add(l.i, h.i == h.j ? l.j : r.j, r.k);
} else if (lh) {
remove(l);
remove(h);
add(l.i, h.i == h.j ? l.j : h.j, h.k);
} else if (hr) {
remove(h);
remove(r);
add(h.i, r.i == r.j ? h.j : r.j, r.k);
}
}
static void update(int i, int d) {
long a = aa[i];
long b = aa[i] += d; // d != 0
if (a == 0) {
add(i, b > 0 ? i + 1 : i, i + 1);
join(i);
} else if (b == 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
if (a > 0) {
add(h.i, i, i);
add(i + 1, h.j, h.k);
} else {
add(h.i, h.j, i);
add(i + 1, i + 1, h.k);
}
} else if (a > 0 && b < 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
add(h.i, i, i + 1);
add(i + 1, h.j, h.k);
join(i);
} else if (a < 0 && b > 0) {
H h = xx.floor(new H(i, i, i));
remove(h);
add(h.i, h.j, i);
add(i, i + 1, h.k);
join(i);
}
}
static int query() {
//return ww.isEmpty() ? 1 : ww.lastKey() + 1;
Integer l = ww.last();
return l == null ? 1 : l + 1;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
aa = new long[n - 1];
int a_ = Integer.parseInt(st.nextToken());
for (int i = 0; i < n - 1; i++) {
int a = Integer.parseInt(st.nextToken());
aa[i] = a - a_;
a_ = a;
}
xx = new Skip<>(n, (p, q) -> p.i - q.i);
ww = new Skip<>(n, (p, q) -> p - q);
init();
int m = Integer.parseInt(br.readLine());
PrintWriter pw = new PrintWriter(System.out);
while (m-- > 0) {
st = new StringTokenizer(br.readLine());
int l = Integer.parseInt(st.nextToken()) - 1;
int r = Integer.parseInt(st.nextToken()) - 1;
int d = Integer.parseInt(st.nextToken());
if (l > 0)
update(l - 1, d);
if (r < n - 1)
update(r, -d);
pw.println(query());
}
pw.close();
}
}
| Java | ["5\n5 5 5 5 5\n3\n1 3 2\n2 2 1\n4 4 1"] | 2 seconds | ["2\n4\n5"] | NoteThe first sample is as follows:After addition of 2 cubes on the top of each towers from the first to the third, the number of cubes in the towers become equal to [7,β7,β7,β5,β5]. The hill with maximum width is [7,β5], thus the maximum width is 2.After addition of 1 cube on the second tower, the number of cubes in the towers become equal to [7,β8,β7,β5,β5]. The hill with maximum width is now [7,β8,β7,β5], thus the maximum width is 4.After addition of 1 cube on the fourth tower, the number of cubes in the towers become equal to [7,β8,β7,β6,β5]. The hill with maximum width is now [7,β8,β7,β6,β5], thus the maximum width is 5. | Java 8 | standard input | [] | a72fcdf5d159f1336f309cf4c6f73297 | The first line contain single integer n (1ββ€βnββ€β3Β·105)Β β the number of towers. The second line contain n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the number of cubes in each tower. The third line contain single integer m (1ββ€βmββ€β3Β·105)Β β the number of additions. The next m lines contain 3 integers each. The i-th of these lines contains integers li, ri and di (1ββ€βlββ€βrββ€βn, 1ββ€βdiββ€β109), that mean that Alyona puts di cubes on the tio of each of the towers from li to ri. | 2,500 | Print m lines. In i-th line print the maximum width of the hills after the i-th addition. | standard output | |
PASSED | a30332ec7ed55f31b49696b7e1286284 | train_004.jsonl | 1479918900 | Alyona has built n towers by putting small cubes some on the top of others. Each cube has size 1βΓβ1βΓβ1. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row.Sometimes Alyona chooses some segment towers, and put on the top of each tower several cubes. Formally, Alyouna chooses some segment of towers from li to ri and adds di cubes on the top of them.Let the sequence a1,βa2,β...,βan be the heights of the towers from left to right. Let's call as a segment of towers al,βalβ+β1,β...,βar a hill if the following condition holds: there is integer k (lββ€βkββ€βr) such that alβ<βalβ+β1β<βalβ+β2β<β...β<βakβ>βakβ+β1β>βakβ+β2β>β...β>βar.After each addition of di cubes on the top of the towers from li to ri, Alyona wants to know the maximum width among all hills. The width of a hill is the number of towers in it. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.*;
/*
_ooOoo_
o8888888o
88" . "88
(| -_- |)
O\ = /O
____/`---'\____
.' \\| |// `.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' | |
\ .-\__ `-` ___/-. /
___`. .' /--.--\ `. . __
."" '< `.___\_<|>_/___.' >'"".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `-. \_ __\ /__ _/ .-` / /
======`-.____`-.___\_____/___.-`____.-'======
`=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pass System Test!
*/
public class E {
private static class Task {
void solve(FastScanner in, PrintWriter out) throws Exception {
int N = in.nextInt();
long[] a = in.nextLongArray(N);
TreeMap<Integer, Integer> left = new TreeMap<>();
int from = 0;
for (int i = 0; i < N; i++) {
if (i == N - 1 || a[i] >= a[i + 1]) {
left.put(from, i);
from = i + 1;
}
}
TreeMap<Integer, Integer> right = new TreeMap<>();
from = N - 1;
for (int i = N - 2; i >= -1; i--) {
if (i < 0 || a[i] <= a[i + 1]) {
right.put(i + 1, from);
from = i;
}
}
RMQ rmq = new RMQ(N);
for (Map.Entry<Integer, Integer> entry : left.entrySet()) {
from = entry.getKey();
int to = entry.getValue();
if (!right.containsKey(to)) continue;
int to2 = right.get(to);
int width = to2 - from + 1;
rmq.update(to, width);
}
long[] d = new long[N - 1];
for (int i = 0; i < N - 1; i++) {
d[i] = a[i + 1] - a[i];
}
int M = in.nextInt();
TreeSet<Integer> tmp = new TreeSet<>();
for (int i = 0; i < M; i++) {
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
long v = in.nextInt();
if (l > 0) {
long prev = d[l - 1];
d[l - 1] += v;
if (prev <= 0 && d[l - 1] > 0) {
// left merge
from = left.floorKey(l - 1);
int to = left.get(l);
left.remove(l);
rmq.update(l, 0);
left.put(from, to);
tmp.add(from);
}
if (prev < 0 && d[l - 1] >= 0) {
// right cut
Map.Entry<Integer, Integer> entry = right.floorEntry(l - 1);
from = entry.getKey();
int to = entry.getValue();
right.put(from, l - 1);
right.put(l, to);
rmq.update(from, 0);
tmp.add(left.floorKey(from));
tmp.add(left.floorKey(l));
}
}
if (r < N - 1) {
long prev = d[r];
d[r] -= v;
if (prev > 0 && d[r] <= 0) {
// left cut
Map.Entry<Integer, Integer> entry = left.floorEntry(r);
from = entry.getKey();
int to = entry.getValue();
left.put(from, r);
left.put(r + 1, to);
rmq.update(to, 0);
tmp.add(from);
tmp.add(r + 1);
}
if (prev >= 0 && d[r] < 0) {
// right merge
from = right.floorKey(r);
int to = right.get(r + 1);
right.remove(r + 1);
right.put(from, to);
rmq.update(from, 0);
tmp.add(left.floorKey(from));
}
}
for (int f : tmp) {
int k = left.get(f);
Integer to = right.get(k);
if (to==null) continue;
rmq.update(k, to - f + 1);
}
tmp.clear();
out.println(rmq.query(0, N + 1));
}
}
class RMQ {
private int N;
private long[] seg;
RMQ(int M) {
N = Integer.highestOneBit(M) * 2;
seg = new long[N * 2];
}
public void update(int k, long value) {
seg[k += N - 1] = value;
while (k > 0) {
k = (k - 1) / 2;
seg[k] = Math.max(seg[k * 2 + 1], seg[k * 2 + 2]);
}
}
//[a, b)
long query(int a, int b) {
return query(a, b, 0, 0, N);
}
long query(int a, int b, int k, int l, int r) {
if (r <= a || b <= l) return 0;
if (a <= l && r <= b) return seg[k];
long x = query(a, b, k * 2 + 1, l, (l + r) / 2);
long y = query(a, b, k * 2 + 2, (l + r) / 2, r);
return Math.max(x, y);
}
}
}
/**
* ???????????????
*/
public static void main(String[] args) throws Exception {
OutputStream outputStream = System.out;
FastScanner in = new FastScanner();
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
private static class FastScanner {
private final InputStream in = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int bufferLength = 0;
private boolean hasNextByte() {
if (ptr < bufferLength) {
return true;
} else {
ptr = 0;
try {
bufferLength = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (bufferLength <= 0) {
return false;
}
}
return true;
}
private int readByte() {
if (hasNextByte()) return buffer[ptr++];
else return -1;
}
private static boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
private void skipUnprintable() {
while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;
}
boolean hasNext() {
skipUnprintable();
return hasNextByte();
}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
long nextLong() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while (true) {
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
} else if (b == -1 || !isPrintableChar(b)) {
return minus ? -n : n;
} else {
throw new NumberFormatException();
}
b = readByte();
}
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] nextDoubleArray(int n) {
double[] array = new double[n];
for (int i = 0; i < n; i++) {
array[i] = nextDouble();
}
return array;
}
double[][] nextDoubleMap(int n, int m) {
double[][] map = new double[n][];
for (int i = 0; i < n; i++) {
map[i] = nextDoubleArray(m);
}
return map;
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) array[i] = nextInt();
return array;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++) array[i] = nextLong();
return array;
}
public String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++) array[i] = next();
return array;
}
public char[][] nextCharMap(int n) {
char[][] array = new char[n][];
for (int i = 0; i < n; i++) array[i] = next().toCharArray();
return array;
}
public int[][] nextIntMap(int n, int m) {
int[][] map = new int[n][];
for (int i = 0; i < n; i++) {
map[i] = nextIntArray(m);
}
return map;
}
}
} | Java | ["5\n5 5 5 5 5\n3\n1 3 2\n2 2 1\n4 4 1"] | 2 seconds | ["2\n4\n5"] | NoteThe first sample is as follows:After addition of 2 cubes on the top of each towers from the first to the third, the number of cubes in the towers become equal to [7,β7,β7,β5,β5]. The hill with maximum width is [7,β5], thus the maximum width is 2.After addition of 1 cube on the second tower, the number of cubes in the towers become equal to [7,β8,β7,β5,β5]. The hill with maximum width is now [7,β8,β7,β5], thus the maximum width is 4.After addition of 1 cube on the fourth tower, the number of cubes in the towers become equal to [7,β8,β7,β6,β5]. The hill with maximum width is now [7,β8,β7,β6,β5], thus the maximum width is 5. | Java 8 | standard input | [] | a72fcdf5d159f1336f309cf4c6f73297 | The first line contain single integer n (1ββ€βnββ€β3Β·105)Β β the number of towers. The second line contain n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the number of cubes in each tower. The third line contain single integer m (1ββ€βmββ€β3Β·105)Β β the number of additions. The next m lines contain 3 integers each. The i-th of these lines contains integers li, ri and di (1ββ€βlββ€βrββ€βn, 1ββ€βdiββ€β109), that mean that Alyona puts di cubes on the tio of each of the towers from li to ri. | 2,500 | Print m lines. In i-th line print the maximum width of the hills after the i-th addition. | standard output | |
PASSED | 336b9571d287b92e7fe97fcc27ed4221 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Main {
static final int mod = (int) (1e9 + 7);
static int[] color, black, white;
static ArrayList<Integer> adjList[];
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
adjList = new ArrayList[n];
for (int i = 0; i < n; i++)
adjList[i] = new ArrayList<>();
for (int i = 1; i < n; i++)
adjList[sc.nextInt()].add(i);
color = sc.nextIntArray(n);
black = new int[n];
white = new int[n];
dfs(0);
out.println(black[0]);
out.flush();
out.close();
}
static void dfs(int u) {
if (color[u] == 0)
white[u] = 1;
else black[u] = 1;
for (int v : adjList[u]) {
dfs(v);
//take v
long b = (1l * white[u] * black[v] + 1l * black[u] * white[v]);
long w = (1l * white[u] * white[v]);
//leave v
b += 1l * black[u] * black[v];
w += 1l * white[u] * black[v];
white[u] = (int) (w % mod);
black[u] = (int) (b % mod);
// System.err.println(u + " " + v + " " + b + " " + w);
}
// System.err.println(u + " " + white[u] + " " + black[u]);
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] ans = new double[n];
for (int i = 0; i < n; i++)
ans[i] = nextDouble();
return ans;
}
public short nextShort() throws IOException {
return Short.parseShort(next());
}
}
} | Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | dca68b48fbc44fe2bf35f69d4adcd501 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.util.*;
public class Main {
private static class Node{
public List<Node> childs=new ArrayList<>();
public int color=0;
public long whiteNum=0;
public long blackNum=0;
}
public static void dfs(Node node){
long mod=1000000007;
for (Node child : node.childs) {
dfs(child);
long old0=node.whiteNum, old1=node.blackNum;
node.whiteNum=old0*(child.whiteNum+child.blackNum)%mod;
node.blackNum=(old1*(child.whiteNum+child.blackNum)+old0*child.blackNum)%mod;
}
}
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
int n=scanner.nextInt();
Node[] vertex=new Node[n];
for (int i = 0; i < n; i++) {
vertex[i]=new Node();
}
for (int i = 0; i < n - 1; i++) {
int p=scanner.nextInt();
vertex[p].childs.add(vertex[i+1]);
}
for (int i = 0; i < n; i++) {
vertex[i].color=scanner.nextInt();
vertex[i].blackNum=vertex[i].color;
vertex[i].whiteNum=vertex[i].color^1;
}
dfs(vertex[0]);
System.out.println(vertex[0].blackNum);
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | e11df0457e44a2b0266aea5ac2fa880d | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.util.*;
public class Main {
private static class Node{
public List<Node> childs=new ArrayList<>();
public int color=0;
public long whiteNum=0;
public long blackNum=0;
}
public static void dfs(Node node){
long mod=1000000007;
for (Node child : node.childs) {
dfs(child);
long old0=node.whiteNum, old1=node.blackNum;
node.whiteNum=old0*(child.whiteNum+child.blackNum)%mod;
node.blackNum=(old1*(child.whiteNum+child.blackNum)+old0*child.blackNum)%mod;
}
}
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
int n=scanner.nextInt();
Node[] vertex=new Node[n];
for (int i = 0; i < n; i++) {
vertex[i]=new Node();
}
for (int i = 0; i < n - 1; i++) {
int p=scanner.nextInt();
vertex[p].childs.add(vertex[i+1]);
}
for (int i = 0; i < n; i++) {
vertex[i].color=scanner.nextInt();
vertex[i].blackNum=vertex[i].color;
vertex[i].whiteNum=vertex[i].color^1;
}
dfs(vertex[0]);
System.out.println(vertex[0].blackNum);
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | ab8fca8b40b5532b5853ca9b81bdfd68 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class CF461B {
static final int MOD = 1000000007;
static long[][] f;
static boolean[] visited;
static int[] color;
static ArrayList<ArrayList<Integer>> adjList;
static void dfs(int u) {
int numAdj = adjList.get(u).size();
visited[u] = true;
f[u][0] = 1; f[u][1] = 0;
for(int i=0; i<numAdj; i++) {
int v = adjList.get(u).get(i);
if (!visited[v]) {
dfs(v);
f[u][1] = (((f[u][1]*f[v][0])%MOD) + (f[u][0]*f[v][1])%MOD)%MOD;
f[u][0] = (f[u][0]*f[v][0])%MOD;
}
}
if (color[u] == 1) f[u][1] = f[u][0];
else f[u][0] = (f[u][0]+f[u][1])%MOD;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int N = in.nextInt();
f = new long[N+1][2];
visited = new boolean[N+1];
Arrays.fill(visited, false);
adjList = new ArrayList<ArrayList<Integer>>();
for(int i=0; i<N; i++) adjList.add(new ArrayList<Integer>());
for(int i=0; i<N-1; i++) {
int a = in.nextInt();
adjList.get(i+1).add(a);
adjList.get(a).add(i+1);
}
color = new int[N+1];
for(int i=0; i<N; i++) color[i] = in.nextInt();
dfs(0);
System.out.println(f[0][1]);
in.close();
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | ba19e0cf5b8ab9c98dfe5496d1e6789e | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | /**
* author: derrick20
* created: 9/23/20 2:21 PM
*/
import java.io.*;
import java.util.*;
public class ApplemanAndTree implements Runnable {
public static void main(String[] args) throws Exception {
new Thread(null, new ApplemanAndTree(), ": )", 1 << 28).start();
}
public void run() {
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int N = sc.nextInt();
int[] par = new int[N];
for (int i = 1; i < N; i++) {
par[i] = sc.nextInt();
}
adjList = new ArrayList[N];
Arrays.setAll(adjList, i -> new ArrayList<>());
for (int i = 1; i < N; i++) {
int u = par[i];
adjList[u].add(i);
}
// System.out.println(Arrays.toString(adjList));
color = sc.nextInts(N);
dp = new long[2][N];
solve(0);
// System.out.println(Arrays.toString(dp[0]));
// System.out.println(Arrays.toString(dp[1]));
out.println(dp[1][0]);
out.close();
}
static ArrayList<Integer>[] adjList;
static long[][] dp;
static int[] color;
static long mod = (long) 1e9 + 7;
static void solve(int node) {
int n = adjList[node].size();
if (n == 0) {
dp[color[node]][node] = 1;
return;
}
int[] children = new int[n + 1];
long[][] prefix = new long[2][n + 1];
long[][] suffix = new long[2][n + 2];
int z = 1;
for (int adj : adjList[node]) {
children[z++] = adj;
solve(adj);
}
prefix[0][0] = 1;
prefix[1][0] = 1;
for (int i = 1; i <= n; i++) {
int c = children[i];
prefix[0][i] = (prefix[0][i - 1] * (dp[0][c] + dp[1][c])) % mod;
prefix[1][i] = (prefix[1][i - 1] * dp[1][c]) % mod;
}
suffix[0][n + 1] = 1;
suffix[1][n + 1] = 1;
for (int i = n; i >= 1; i--) {
int c = children[i];
suffix[0][i] = (suffix[0][i + 1] * (dp[0][c] + dp[1][c])) % mod;
suffix[1][i] = (suffix[1][i + 1] * dp[1][c]) % mod;
}
if (color[node] == 0) {
dp[0][node] = prefix[0][n];
long sum = 0;
int mergeWith = 1 - color[node];
if (node == 8) {
System.out.println();
}
for (int i = 1; i <= n; i++) {
int skip = children[i];
long pre = prefix[0][i - 1];
long suf = suffix[0][i + 1];
long rem = (pre * suf) % mod;
long amt = (dp[mergeWith][skip] * rem) % mod;
sum = (sum + amt) % mod;
}
dp[1][node] = sum;
} else {
dp[0][node] = 0;
dp[1][node] = prefix[0][n];
}
}
static class FastScanner {
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static void ASSERT(boolean assertion, String message) {
if (!assertion) throw new AssertionError(message);
}
static void ASSERT(boolean assertion) {
if (!assertion) throw new AssertionError();
}
} | Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 5e3634aa25dcf4180c3aaa852f276609 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes |
import java.util.*;
import java.io.*;
/**
*
* @author usquare
*/
public class ProblemA {
static int mod = (int) (1e9+7);
static InputReader in;
static PrintWriter out;
static ArrayList<Integer>[] g;
static long[][] dp;
static int[] arr;
static long[] tmp;
static void dfs(int u){
dp[u][arr[u]] = 1;
for(int v:g[u]){
dfs(v);
tmp[0] = tmp[1] = 0;
tmp[0] = mul(dp[u][0],dp[v][0]+dp[v][1]);
tmp[1] = mul(dp[u][1],dp[v][0]+dp[v][1]);
tmp[1] = add(tmp[1],mul(dp[u][0],dp[v][1]));
for(int i=0;i<2;i++) dp[u][i] = tmp[i];
}
}
public static void main(String[] args) throws FileNotFoundException {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int n = in.nextInt();
g = new ArrayList[n];
dp = new long[n][2];
tmp = new long[2];
for(int i=0;i<n;i++) g[i] = new ArrayList<>();
for(int i=1;i<n;i++){
int p = in.nextInt();
g[p].add(i);
}
arr = in.nextIntArray(n);
dfs(0);
out.println(dp[0][1]);
out.close();
}
static class Pair implements Comparable<Pair>{
int x;
int y,i;
Pair (int x,int y,int i){
this.x=x;
this.y=y;
this.i=i;
}
Pair (int x,int y){
this.x=x;
this.y=y;
}
public int compareTo(Pair o) {
return Long.compare(this.y,o.y);
//return 0;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.x == x && p.y == y && p.i==i;
}
return false;
}
@Override
public String toString() {
return x+" "+y+" "+i;
}
public int hashCode() {
return new Long(x).hashCode() * 31 + new Long(y).hashCode()+new Long(i).hashCode()*37;
}
}
static class Merge {
public static void sort(long inputArr[]) {
int length = inputArr.length;
doMergeSort(inputArr,0, length - 1);
}
private static void doMergeSort(long[] arr,int lowerIndex, int higherIndex) {
if (lowerIndex < higherIndex) {
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
doMergeSort(arr,lowerIndex, middle);
doMergeSort(arr,middle + 1, higherIndex);
mergeParts(arr,lowerIndex, middle, higherIndex);
}
}
private static void mergeParts(long[]array,int lowerIndex, int middle, int higherIndex) {
long[] temp=new long[higherIndex-lowerIndex+1];
for (int i = lowerIndex; i <= higherIndex; i++) {
temp[i-lowerIndex] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex) {
if (temp[i-lowerIndex] < temp[j-lowerIndex]) {
array[k] = temp[i-lowerIndex];
i++;
} else {
array[k] = temp[j-lowerIndex];
j++;
}
k++;
}
while (i <= middle) {
array[k] = temp[i-lowerIndex];
k++;
i++;
}
while(j<=higherIndex){
array[k]=temp[j-lowerIndex];
k++;
j++;
}
}
}
static long add(long a,long b){
long x=(a+b);
while(x>=mod) x-=mod;
return x;
}
static long sub(long a,long b){
long x=(a-b);
while(x<0) x+=mod;
return x;
}
static long mul(long a,long b){
a%=mod;
b%=mod;
long x=(a*b);
return x%mod;
}
static boolean isPal(String s){
for(int i=0, j=s.length()-1;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j)) return false;
}
return true;
}
static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long gcd(long x,long y){
if(y==0)
return x;
else
return gcd(y,x%y);
}
static int gcd(int x,int y){
if(y==0)
return x;
else
return gcd(y,x%y);
}
static long gcdExtended(long a,long b,long[] x){
if(a==0){
x[0]=0;
x[1]=1;
return b;
}
long[] y=new long[2];
long gcd=gcdExtended(b%a, a, y);
x[0]=y[1]-(b/a)*y[0];
x[1]=y[0];
return gcd;
}
static long mulmod(long a,long b,long m) {
if (m <= 1000000009) return a * b % m;
long res = 0;
while (a > 0) {
if ((a&1)!=0) {
res += b;
if (res >= m) res -= m;
}
a >>= 1;
b <<= 1;
if (b >= m) b -= m;
}
return res;
}
static int abs(int a,int b){
return (int)Math.abs(a-b);
}
public static long abs(long a,long b){
return (long)Math.abs(a-b);
}
static int max(int a,int b){
if(a>b)
return a;
else
return b;
}
static int min(int a,int b){
if(a>b)
return b;
else
return a;
}
static long max(long a,long b){
if(a>b)
return a;
else
return b;
}
static long min(long a,long b){
if(a>b)
return b;
else
return a;
}
static long pow(long n,long p,long m){
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
static long pow(long n,long p){
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | d4fd722e9159800cbce32ffa42b11ba7 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Queue;
public class Main {
static int N = 100005;
int n;
int[] b = new int[N];
long[][] dp = new long[N][2];//0葨瀺δΈε±δΊζδΈͺι»ηΉ
void dfs(int u, int fa){
dp[u][b[u]] = 1;
for(int i = head[u]; i != -1; i = edge[i].nex){
int v = edge[i].to; if(v == fa)continue;
dfs(v, u);
dp[u][1]=(dp[u][1]*dp[v][0]%mod+dp[u][1]*dp[v][1]%mod+dp[u][0]*dp[v][1]%mod)%mod;
dp[u][0]=(dp[u][0]*dp[v][0]%mod+dp[u][0]*dp[v][1]%mod)%mod;
}
}
void input(){
n = cin.nextInt();
for(int i = 0; i < n; i++)head[i] = -1; edgenum = 0;
for(int i = 1; i < n; i++){
int u = cin.nextInt();
add(u, i); add(i, u);
}
for(int i = 0; i < n; i++)b[i] = cin.nextInt();
}
void work() {
input();
dfs(0,0);
out.println(dp[0][1]%mod);
}
Main() {
cin = new Scanner(System.in);
out = new PrintWriter(System.out);
}
public static void main(String[] args) {
Main e = new Main();
e.work();
out.close();
}
public Scanner cin;
public static PrintWriter out;
DecimalFormat df=new DecimalFormat("0.0000");
static int inf = (int) 1e9;
static long inf64 = (long) 1e18;
static double eps = 1e-8;
static int mod = 1000000007 ;
class Edge{
int from, to, nex;
Edge(){}
Edge(int from, int to, int nex){
this.from = from;
this.to = to;
this.nex = nex;
}
}
Edge[] edge = new Edge[N<<1];
int[] head = new int[N];
int edgenum;
void add(int u, int v){
edge[edgenum] = new Edge(u, v, head[u]);
head[u] = edgenum++;
}
int upper_bound(int[] A, int l, int r, int val) {// upper_bound(A+l,A+r,val)-A;
int pos = r;
r--;
while (l <= r) {
int mid = (l + r) >> 1;
if (A[mid] <= val) {
l = mid + 1;
} else {
pos = mid;
r = mid - 1;
}
}
return pos;
}
int Pow(int x, int y) {
int ans = 1;
while (y > 0) {
if ((y & 1) > 0)
ans *= x;
y >>= 1;
x = x * x;
}
return ans;
}
int Pow_Mod(int x, int y, int mod) {
int ans = 1;
while (y > 0) {
if ((y & 1) > 0)
ans *= x;
ans %= mod;
y >>= 1;
x = x * x;
x %= mod;
}
return ans;
}
long Pow(long x, long y) {
long ans = 1;
while (y > 0) {
if ((y & 1) > 0)
ans *= x;
y >>= 1;
x = x * x;
}
return ans;
}
long Pow_Mod(long x, long y, long mod) {
long ans = 1;
while (y > 0) {
if ((y & 1) > 0)
ans *= x;
ans %= mod;
y >>= 1;
x = x * x;
x %= mod;
}
return ans;
}
int max(int x, int y) {
return x > y ? x : y;
}
int min(int x, int y) {
return x < y ? x : y;
}
double max(double x, double y) {
return x > y ? x : y;
}
double min(double x, double y) {
return x < y ? x : y;
}
long max(long x, long y) {
return x > y ? x : y;
}
long min(long x, long y) {
return x < y ? x : y;
}
int abs(int x) {
return x > 0 ? x : -x;
}
double abs(double x) {
return x > 0 ? x : -x;
}
long abs(long x) {
return x > 0 ? x : -x;
}
boolean zero(double x) {
return abs(x) < eps;
}
} | Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 5e0a83f0b4deb122011fd2e95cd63850 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | // practice with rainboy
import java.io.*;
import java.util.*;
public class CF461B extends PrintWriter {
CF461B() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF461B o = new CF461B(); o.main(); o.flush();
}
static final int MD = 1000000007;
int[] next, jj; int l_ = 1;
int link(int l, int j) { next[l_] = l; jj[l_] = j; return l_++; }
int[] ao, xx, dp0, dp1, pp, qq;
void init(int n, int m) {
next = new int[1 + m * 2];
jj = new int[1 + m * 2];
ao = new int[n];
xx = new int[n];
dp0 = new int[n];
dp1 = new int[n];
pp = new int[n];
qq = new int[n];
}
void dfs(int i) {
int x = xx[i], c = 0;
for (int l = ao[i]; l != 0; l = next[l]) {
int j = jj[l];
dfs(j);
c++;
}
if (c == 0) {
dp0[i] = 1 - x;
dp1[i] = x;
return;
}
for (int l = ao[i], h = 0; l != 0; l = next[l]) {
int j = jj[l];
pp[h] = qq[h] = (dp0[j] + dp1[j]) % MD;
h++;
}
for (int h = 1; h < c; h++)
pp[h] = (int) ((long) pp[h] * pp[h - 1] % MD);
for (int h = c - 2; h >= 0; h--)
qq[h] = (int) ((long) qq[h] * qq[h + 1] % MD);
if (x == 1) {
dp1[i] = pp[c - 1];
dp0[i] = 0;
} else {
dp0[i] = pp[c - 1];
long sum = 0;
for (int l = ao[i], h = 0; l != 0; l = next[l]) {
int j = jj[l];
long p = h == 0 ? 1 : pp[h - 1];
long q = h == c - 1 ? 1 : qq[h + 1];
sum = (sum + dp1[j] * p % MD * q) % MD;
h++;
}
dp1[i] = (int) sum;
}
}
void main() {
int n = sc.nextInt();
init(n, n - 1);
for (int j = 1; j < n; j++) {
int i = sc.nextInt();
ao[i] = link(ao[i], j);
}
for (int i = 0; i < n; i++)
xx[i] = sc.nextInt();
dfs(0);
println(dp1[0]);
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 050a5bf61ca88cf1e0c8f5ea1c02eaa4 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;
/**
* @author Roman Elizarov
*/
public class Round_263_B {
public static void main(String[] args) {
new Round_263_B().go();
}
static final int MOD = 1000000007;
int n;
int[] p;
int[] c;
void go() {
// read input
Scanner in = new Scanner(System.in);
n = in.nextInt();
p = new int[n];
for (int i = 1; i < n; i++)
p[i] = in.nextInt();
c = new int[n];
for (int i = 0; i < n; i++)
c[i] = in.nextInt();
// solve
int result = solve();
// write result
PrintStream out = System.out;
out.println(result);
}
int[] nChildren;
int[][] children;
int solve() {
nChildren = new int[n];
for (int i = 1; i < n; i++)
nChildren[p[i]]++;
children = new int[n][];
for (int i = 0; i < n; i++) {
children[i] = new int[nChildren[i]];
nChildren[i] = 0;
}
for (int i = 1; i < n; i++)
children[p[i]][nChildren[p[i]]++] = i;
return subtree(0)[1];
}
private int[] subtree(int i) {
int[] r;
if (c[i] == 0) {
if (nChildren[i] == 0)
r = new int[] { 1, 0 };
else {
r = subtree(children[i][0]);
r = new int[] {
add(r[1], r[0]),
r[1]
};
for (int k = 1; k < nChildren[i]; k++) {
int[] s = subtree(children[i][k]);
r = new int[] {
add(mul(r[0], s[1]), mul(r[0], s[0])),
add(mul(r[1], s[1]), mul(r[0], s[1]), mul(r[1], s[0]))
};
}
}
} else {
// c[i] == 1
if (nChildren[i] == 0)
r = new int[] { 0, 1 };
else {
r = subtree(children[i][0]);
r = new int[] {
0,
add(r[1], r[0]) };
for (int k = 1; k < nChildren[i]; k++) {
int[] s = subtree(children[i][k]);
r = new int[] {
0,
add(mul(r[1], s[1]), mul(r[1], s[0]))
};
}
}
}
return r;
}
int mul(long a, long b) {
return (int)(a * b % MOD);
}
int add(long a, long b) {
return (int)((a + b) % MOD);
}
int add(long a, long b, long c) {
return (int)((a + b + c) % MOD);
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 9c944281dda4912292dc7f309b75bdee | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import javax.print.DocFlavor;
import java.util.*;
import java.io.*;
public class Main {
static ArrayList<Integer>graph[]=new ArrayList[120000];
public static void main(String[] args) throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new PrintStream(System.out));
int n=Integer.parseInt(f.readLine());
for(int i=0;i<n;i++){
graph[i]=new ArrayList<>();
}
StringTokenizer st=new StringTokenizer(f.readLine());
for(int i=0;i<n-1;i++){
int a=Integer.parseInt(st.nextToken());
graph[i+1].add(a);
graph[a].add(i+1);
}
st=new StringTokenizer(f.readLine());
for(int i=0;i<n;i++){
arr[i]=Integer.parseInt(st.nextToken());
}
dfs(0,-1);
System.out.println(dp[0][1]);
f.close();
out.close();
}
static long MOD=1000000007;
static long[][]dp=new long[120000][2];
static void dfs(int curr, int last){
dp[curr][0]=1-arr[curr];
dp[curr][1]=arr[curr];
for(int i:graph[curr]){
if(i!=last) {
dfs(i, curr);
long temp1 = dp[curr][0];
long temp2 = dp[curr][1];
dp[curr][0] = 0;
dp[curr][1] = 0;
//next is part of it
dp[curr][1] += temp1 * dp[i][1];
dp[curr][1] += temp2 * dp[i][0];
//
dp[curr][0] += temp1 * dp[i][1];
dp[curr][1] += temp2 * dp[i][1];
dp[curr][0] += temp1 * dp[i][0];
}
dp[curr][0]%=MOD;
dp[curr][1]%=MOD;
}
}
static int[]arr=new int[120000];
}
class pair implements Comparable <pair>{
int num;
int idx;
public int compareTo(pair other){
return num- other.num;
}
pair(int a, int b)
{
num=a;
idx=b;
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 79120d28aed988b7cc6d976f43a02e9f | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
BApplemanAndTree solver = new BApplemanAndTree();
solver.solve(1, in, out);
out.close();
}
static class BApplemanAndTree {
ArrayList<Integer>[] childs;
long[][] dp;
int[] x;
private int mod = (int) 1e9 + 7;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.readInt();
dp = new long[n][2];
childs = new ArrayList[n];
for (int i = 0; i < childs.length; i++) childs[i] = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int p = in.readInt();
childs[p].add(i + 1);
}
x = in.readIntArray(n);
go(0);
out.println(dp[0][1]);
}
void go(int pos) {
dp[pos][0] = 1;
dp[pos][1] = 0;
for (int i : childs[pos]) {
go(i);
dp[pos][1] = ((dp[pos][0] * dp[i][1]) % mod + (dp[pos][1] * dp[i][0]) % mod) % mod;
dp[pos][0] = (dp[pos][0] * dp[i][0]) % mod;
}
if (x[pos] == 0) {
dp[pos][0] = (dp[pos][0] + dp[pos][1]) % mod;
} else {
dp[pos][1] = dp[pos][0];
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int 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 isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] readIntArray(int size) {
int[] ans = new int[size];
for (int i = 0; i < size; i++) ans[i] = readInt();
return ans;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | e66ed2e6f71982abce4abc88c6cd4799 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class R263qBApplemanAndTree {
static int n;
static ArrayList<Integer> g[];
static long dp[][];
static int x[];
static final int mod = (int)(1e9 + 7);
@SuppressWarnings("unchecked")
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter w = new PrintWriter(System.out);
n = ip(br.readLine());
g = new ArrayList[n];
for(int i=0;i<n;i++)
g[i] = new ArrayList<Integer>();
StringTokenizer st1 = new StringTokenizer(br.readLine());
for(int i=1;i<n;i++)
g[ip(st1.nextToken())].add(i);
x = new int[n];
StringTokenizer st2 = new StringTokenizer(br.readLine());
for(int i=0;i<n;i++)
x[i] = ip(st2.nextToken());
dp = new long[n][2];
for(int i=0;i<n;i++) dp[i][0] = dp[i][1] = -1; //dp[i][j] = ans for subtree[i] with j needed
w.println(solve(0,1));
w.close();
}
public static long solve(int curr,int state){
//System.out.println(curr + " " + state);
if(dp[curr][state] == -1){
long ans = 0;
if(state == 1){ //if 1 needed
if(x[curr] == 0){
long temp = 1;
for(int next : g[curr])
temp = (temp * (solve(next,1) + solve(next,0))) % mod;
for(int next : g[curr]){
long temp2 = (temp * inv(solve(next,0) + solve(next,1))) % mod;
temp2 = (temp2 * solve(next,1)) % mod;
ans += temp2;
if(ans >= mod)
ans -= mod;
}
}
else{
ans = 1;
for(int next : g[curr])
ans = (ans * (solve(next,0) + solve(next,1))) % mod;
}
}
else{
if(x[curr] == 0){
ans = 1;
for(int next : g[curr])
ans = (ans * (solve(next,1) + solve(next,0))) % mod;
}
else
ans = 0;
}
dp[curr][state] = ans;
//System.out.println(curr + " " + state + " " + dp[curr][state] + " " + g[curr]);
}
return dp[curr][state];
}
public static long inv(long x){
return pow((int)(x%mod),mod-2);
}
public static long pow(int a,int b){
if(b == 0)
return 1;
long t = pow(a,b>>1);
t = (t * t) % mod;
if( (b & 1) != 0)
t = (t * a) % mod;
return t;
}
public static int ip(String s){
return Integer.parseInt(s);
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 1dc024cb1c52a136c58048fb269a33d5 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class _461B {
static final long MOD = 1000000007;
static long pow(long a, long n) {
a %= MOD;
long ans = 1;
while (n > 0) {
if (n % 2 == 1) ans = ans * a % MOD;
a = a * a % MOD;
n /= 2;
}
return ans;
}
static long inv(long a) {
return pow(a, MOD - 2);
}
static long[][] f;
static int n;
static List<Integer>[] g;
static int[] color;
static void dfs(int u, int parent) {
for (int v : g[u])
if (v != parent)
dfs(v, u);
if (color[u] == 0) {
f[u][0] = 1;
for (int v : g[u])
if (v != parent) f[u][0] = f[u][0] * ((f[v][0] + f[v][1]) % MOD) % MOD;
long prod = f[u][0];
f[u][1] = 0;
for (int v : g[u])
if (v != parent) f[u][1] = (f[u][1] + f[v][1] * inv(f[v][0] + f[v][1]) % MOD) % MOD;
f[u][1] = f[u][1] * prod % MOD;
} else if (color[u] == 1) {
f[u][0] = 0;
f[u][1] = 1;
for (int v : g[u])
if (v != parent) f[u][1] = f[u][1] * ((f[v][0] + f[v][1]) % MOD) % MOD;
} else assert (false);
}
public static void main(String[] args) throws Exception {
Reader.init(System.in);
BufferedWriter cout = new BufferedWriter(new OutputStreamWriter(System.out));
n = Reader.nextInt();
f = new long[n][2];
g = new List[n];
color = new int[n];
for (int i = 0; i < n; i++) g[i] = new ArrayList<>();
for (int i = 1; i < n; i++) {
int u = Reader.nextInt();
int v = i;
g[u].add(v);
g[v].add(u);
}
for (int i = 0; i < n; i++) color[i] = Reader.nextInt();
dfs(0, -1);
System.out.println(f[0][1]);
// for (int i = 0; i < n; i++) System.out.println(i + ": " + f[i][0] + " " + f[i][1]);
cout.close();
}
static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
final U _1;
final V _2;
private Pair(U key, V val) {
this._1 = key;
this._2 = val;
}
public static <U extends Comparable<U>, V extends Comparable<V>> Pair<U, V> instanceOf(U _1, V _2) {
return new Pair<U, V>(_1, _2);
}
@Override
public String toString() {
return _1 + " " + _2;
}
@Override
public int hashCode() {
int res = 17;
res = res * 31 + _1.hashCode();
res = res * 31 + _2.hashCode();
return res;
}
@Override
public int compareTo(Pair<U, V> that) {
int res = this._1.compareTo(that._1);
if (res < 0 || res > 0) return res;
else return this._2.compareTo(that._2);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Pair)) return false;
Pair<?, ?> that = (Pair<?, ?>) obj;
return _1.equals(that._1) && _2.equals(that._2);
}
}
/**
* Class for buffered reading int and double values
*/
static class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/**
* call this method to initialize reader for InputStream
*/
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/**
* get next word
*/
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
// TODO add check for eof if necessary
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
static class ArrayUtil {
static void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(long[] a, int i, int j) {
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(double[] a, int i, int j) {
double tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(char[] a, int i, int j) {
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(boolean[] a, int i, int j) {
boolean tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void reverse(int[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(long[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(double[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(char[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(boolean[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static long sum(int[] a) {
int sum = 0;
for (int i : a)
sum += i;
return sum;
}
static long sum(long[] a) {
long sum = 0;
for (long i : a)
sum += i;
return sum;
}
static double sum(double[] a) {
double sum = 0;
for (double i : a)
sum += i;
return sum;
}
static int max(int[] a) {
int max = Integer.MIN_VALUE;
for (int i : a)
if (i > max) max = i;
return max;
}
static int min(int[] a) {
int min = Integer.MAX_VALUE;
for (int i : a)
if (i < min) min = i;
return min;
}
static long max(long[] a) {
long max = Long.MIN_VALUE;
for (long i : a)
if (i > max) max = i;
return max;
}
static long min(long[] a) {
long min = Long.MAX_VALUE;
for (long i : a)
if (i < min) min = i;
return min;
}
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 63edca737faec73650bdcb9a2271687c | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes |
//package round263;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class B {
InputStream is;
PrintWriter out;
String INPUT = "";
final int mod = 1000000007;
void solve() {
int n = ni();
int[] from = new int[n - 1];
int[] to = new int[n - 1];
for (int i = 0; i < n - 1; i++) {
from[i] = ni();
to[i] = i + 1;
}
int[][] g = packU(n, from, to);
int[] f = na(n);
int root = -1;
for (int i = 0; i < n; i++) {
if (f[i] == 1) {
root = i;
break;
}
}
if (root == -1) {
out.println(1);
return;
}
int[][] pars = parents3(g, root);
int[] par = pars[0], ord = pars[1];
long[][] dp = new long[n][2];
for (int i = n - 1; i >= 0; i--) {
int cur = ord[i];
if (f[cur] == 0) {
long z = 1, o = 0;
for(int e : g[cur]) {
if(e != par[cur]) {
o = (o * (dp[e][0] + dp[e][1]) + z * dp[e][1]) % mod;
z = z * (dp[e][0] + dp[e][1]) % mod;
}
}
dp[cur][0] = z;
dp[cur][1] = o;
} else {
long o = 1;
for (int e : g[cur]) {
if (e != par[cur]) {
o = o * (dp[e][0] + dp[e][1]) % mod;
}
}
dp[cur][0] = 0;
dp[cur][1] = o;
}
}
out.println(dp[root][1]);
}
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;
}
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 };
}
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 B().run();
}
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) {
if (!oj)
System.out.println(Arrays.deepToString(o));
}
} | Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | b1fc12ff67305f658caa9b92a3379b19 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.io.*;
import java.util.*;
public class B461 {
static ArrayList <Integer> [] g = new ArrayList [100010];
static int color [] = new int [100010];
final static int mod = 1000000007;
static long [][] fn = new long [100010][2];
static long modpower(long b, long e) {
if(e == 0) return 1;
if((e % 2) == 1) return (modpower(b, e - 1) * b) % mod;
long m = modpower(b, e / 2);
return (m * m) % mod;
}
static long inverse(long x) {
return modpower(x, mod - 2);
}
static long dp(int x, int take) {
if(fn[x][take] != -1) return fn[x][take];
long perm = 1;
for(Integer i : g[x]) {
perm *= dp(i, 0) + dp(i, 1);
perm %= mod;
}
long ans;
if(color[x] == 1) {
if(take == 1) ans = perm;
else ans = 0;
} else if (take == 0) {
ans = perm;
} else {
ans = 0;
for(Integer i : g[x]) {
long r = (perm * inverse( dp(i, 0) + dp(i, 1) )) % mod;
r *= dp(i, 1);
r %= mod;
ans += r;
ans %= mod;
}
}
return fn[x][take] = ans;
}
public static void main(String[] args) {
Reader in = new Reader ();
int n = in.nextInt();
for(int i = 0; i <= n; i++) {
for(int j = 0; j <= 1; j++) {
fn[i][j] = -1;
}
}
for(int i = 0; i <= n; i++) g[i] = new ArrayList <Integer> ();
for(int i = 1; i < n; i++) {
int p = in.nextInt();
g[p].add(i);
}
for(int i = 0; i < n; i++) {
color[i] = in.nextInt();
}
long ans = dp(0, 1);
System.out.println(ans);
}
static class Reader {
BufferedReader a;
StringTokenizer b;
Reader () {
a = new BufferedReader (new InputStreamReader (System.in));
}
String next () {
while(b == null || !b.hasMoreTokens()) {
try {
b = new StringTokenizer (a.readLine());
} catch (IOException e) {
e.printStackTrace ();
}
}
return b.nextToken ();
}
int nextInt () {
return Integer.parseInt(this.next());
}
}
} | Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 99b951669684b6e857befaf42c41128c | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | // package Quarantine;
import javafx.util.Pair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class AppleManAndTree {
public static void main(String[] args)throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
ArrayList<Integer> tree[]=new ArrayList[n];
for(int i=0;i<n;i++){
tree[i]=new ArrayList<>();
}
StringTokenizer st=new StringTokenizer(br.readLine());
for(int i=0;i<=n-2;i++){
int x=Integer.parseInt(st.nextToken());
tree[i+1].add(x);
tree[x].add(i+1);
}
int val[]=new int[n];
st=new StringTokenizer(br.readLine());
for(int i=0;i<n;i++){
val[i]=Integer.parseInt(st.nextToken());
}
long ans[]=dfs(tree,0,new boolean[n],val,1000000007);
System.out.println(ans[1]);
}
public static long[] dfs(ArrayList<Integer> tree[],int curr,boolean visited[],int val[],int mod){
long ans[]=new long[2];
visited[curr]=true;
if(val[curr]==1){
ans[1]=1;
for(int j:tree[curr]){
if(!visited[j]){
long small[]=dfs(tree,j,visited,val,mod);
ans[1]=(ans[1]*(small[0]+small[1]))%mod;
}
}
}
else{
ans[0]=1;
ArrayList<Pair<Long,Long>> temp=new ArrayList<>();
for(int j:tree[curr]){
if(!visited[j]){
long small[]=dfs(tree,j,visited,val,mod);
ans[0]=(ans[0]*(small[0]+small[1]))%mod;
temp.add(new Pair<>(small[0],small[1]));
}
}
for(Pair<Long,Long> p:temp){
long t=(p.getValue()*ans[0])%mod;
t=(t*modexp(p.getValue()+p.getKey(),mod-2,mod))%mod;
ans[1]=(ans[1]+t)%mod;
}
}
return ans;
}
public static long modexp(long a,long power,int mod){
if(power==0){
return 1;
}
if(power==1){
return a;
}
long small=modexp(a,power/2,mod);
long ans=(small%mod*small%mod)%mod;
if(power%2!=0){
ans=(ans%mod*a%mod)%mod;
}
return ans;
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 006a44ced807ac3aadc1b5c489cdf88b | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.List;
import java.math.BigInteger;
import java.io.OutputStream;
import java.util.Iterator;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.Arrays;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.Comparator;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Egor Kulikov (egor@egork.net)
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
static final long MOD = (long) (1e9 + 7);
long[][] answer;
Graph graph;
int count;
int[] isBlack;
public void solve(int testNumber, InputReader in, OutputWriter out) {
count = in.readInt();
graph = new Graph(count);
for (int i = 1; i < count; i++) {
graph.addSimpleEdge(in.readInt(), i);
}
isBlack = IOUtils.readIntArray(in, count);
answer = new long[2][count];
ArrayUtils.fill(answer, -1);
out.printLine(dfs(1, 0));
}
private long dfs(int needBlack, int id) {
if (answer[needBlack][id] != -1) {
return answer[needBlack][id];
}
if (needBlack == 0 && isBlack[id] == 1) {
return answer[needBlack][id] = 0;
}
if (isBlack[id] == 1 || needBlack == 0) {
answer[needBlack][id] = 1;
for (int i = graph.firstOutbound(id); i != -1; i = graph.nextOutbound(i)) {
answer[needBlack][id] *= dfs(0, graph.destination(i)) + dfs(1, graph.destination(i));
answer[needBlack][id] %= MOD;
}
} else {
IntList black = new IntArrayList();
IntList total = new IntArrayList();
for (int i = graph.firstOutbound(id); i != -1; i = graph.nextOutbound(i)) {
black.add((int) dfs(1, graph.destination(i)));
total.add((int) ((dfs(0, graph.destination(i)) + dfs(1, graph.destination(i))) % MOD));
}
int zeroes = total.count(0);
if (zeroes >= 2) {
return answer[needBlack][id] = 0;
}
if (zeroes == 1) {
answer[needBlack][id] = 1;
for (int i = 0; i < black.size(); i++) {
if (total.get(i) == 0) {
answer[needBlack][id] *= black.get(i);
} else {
answer[needBlack][id] *= total.get(i);
}
answer[needBlack][id] %= MOD;
}
return answer[needBlack][id];
}
long product = 1;
for (int i = 0; i < total.size(); i++) {
product *= total.get(i);
product %= MOD;
}
answer[needBlack][id] = 0;
for (int i = 0; i < black.size(); i++) {
answer[needBlack][id] += product * IntegerUtils.reverse(total.get(i), MOD) % MOD * black.get(i) % MOD;
}
answer[needBlack][id] %= MOD;
}
return answer[needBlack][id];
}
}
class Graph {
public static final int REMOVED_BIT = 0;
protected int vertexCount;
protected int edgeCount;
private int[] firstOutbound;
private int[] firstInbound;
private Edge[] edges;
private int[] nextInbound;
private int[] nextOutbound;
private int[] from;
private int[] to;
private long[] weight;
private long[] capacity;
private int[] reverseEdge;
private int[] flags;
public Graph(int vertexCount) {
this(vertexCount, vertexCount);
}
public Graph(int vertexCount, int edgeCapacity) {
this.vertexCount = vertexCount;
firstOutbound = new int[vertexCount];
Arrays.fill(firstOutbound, -1);
from = new int[edgeCapacity];
to = new int[edgeCapacity];
nextOutbound = new int[edgeCapacity];
flags = new int[edgeCapacity];
}
public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) {
ensureEdgeCapacity(edgeCount + 1);
if (firstOutbound[fromID] != -1)
nextOutbound[edgeCount] = firstOutbound[fromID];
else
nextOutbound[edgeCount] = -1;
firstOutbound[fromID] = edgeCount;
if (firstInbound != null) {
if (firstInbound[toID] != -1)
nextInbound[edgeCount] = firstInbound[toID];
else
nextInbound[edgeCount] = -1;
firstInbound[toID] = edgeCount;
}
this.from[edgeCount] = fromID;
this.to[edgeCount] = toID;
if (capacity != 0) {
if (this.capacity == null)
this.capacity = new long[from.length];
this.capacity[edgeCount] = capacity;
}
if (weight != 0) {
if (this.weight == null)
this.weight = new long[from.length];
this.weight[edgeCount] = weight;
}
if (reverseEdge != -1) {
if (this.reverseEdge == null) {
this.reverseEdge = new int[from.length];
Arrays.fill(this.reverseEdge, 0, edgeCount, -1);
}
this.reverseEdge[edgeCount] = reverseEdge;
}
if (edges != null)
edges[edgeCount] = createEdge(edgeCount);
return edgeCount++;
}
protected final GraphEdge createEdge(int id) {
return new GraphEdge(id);
}
public final int addFlowWeightedEdge(int from, int to, long weight, long capacity) {
if (capacity == 0) {
return addEdge(from, to, weight, 0, -1);
} else {
int lastEdgeCount = edgeCount;
addEdge(to, from, -weight, 0, lastEdgeCount + entriesPerEdge());
return addEdge(from, to, weight, capacity, lastEdgeCount);
}
}
protected int entriesPerEdge() {
return 1;
}
public final int addWeightedEdge(int from, int to, long weight) {
return addFlowWeightedEdge(from, to, weight, 0);
}
public final int addSimpleEdge(int from, int to) {
return addWeightedEdge(from, to, 0);
}
public final int firstOutbound(int vertex) {
int id = firstOutbound[vertex];
while (id != -1 && isRemoved(id))
id = nextOutbound[id];
return id;
}
public final int nextOutbound(int id) {
id = nextOutbound[id];
while (id != -1 && isRemoved(id))
id = nextOutbound[id];
return id;
}
public final int destination(int id) {
return to[id];
}
public final boolean flag(int id, int bit) {
return (flags[id] >> bit & 1) != 0;
}
public final boolean isRemoved(int id) {
return flag(id, REMOVED_BIT);
}
protected void ensureEdgeCapacity(int size) {
if (from.length < size) {
int newSize = Math.max(size, 2 * from.length);
if (edges != null)
edges = resize(edges, newSize);
from = resize(from, newSize);
to = resize(to, newSize);
nextOutbound = resize(nextOutbound, newSize);
if (nextInbound != null)
nextInbound = resize(nextInbound, newSize);
if (weight != null)
weight = resize(weight, newSize);
if (capacity != null)
capacity = resize(capacity, newSize);
if (reverseEdge != null)
reverseEdge = resize(reverseEdge, newSize);
flags = resize(flags, newSize);
}
}
protected final int[] resize(int[] array, int size) {
int[] newArray = new int[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private long[] resize(long[] array, int size) {
long[] newArray = new long[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private Edge[] resize(Edge[] array, int size) {
Edge[] newArray = new Edge[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
protected class GraphEdge implements Edge {
protected int id;
protected GraphEdge(int id) {
this.id = id;
}
}
}
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 isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
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 close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
}
class ArrayUtils {
public static void fill(long[][] array, long value) {
for (long[] row : array)
Arrays.fill(row, value);
}
}
abstract class IntList extends IntCollection implements Comparable<IntList> {
public abstract int get(int index);
public IntIterator iterator() {
return new IntIterator() {
private int size = size();
private int index = 0;
public int value() throws NoSuchElementException {
if (!isValid())
throw new NoSuchElementException();
return get(index);
}
public void advance() throws NoSuchElementException {
if (!isValid())
throw new NoSuchElementException();
index++;
}
public boolean isValid() {
return index < size;
}
};
}
public int hashCode() {
int hashCode = 1;
for (IntIterator i = iterator(); i.isValid(); i.advance())
hashCode = 31 * hashCode + i.value();
return hashCode;
}
public boolean equals(Object obj) {
if (!(obj instanceof IntList))
return false;
IntList list = (IntList)obj;
if (list.size() != size())
return false;
IntIterator i = iterator();
IntIterator j = list.iterator();
while (i.isValid()) {
if (i.value() != j.value())
return false;
i.advance();
j.advance();
}
return true;
}
public int compareTo(IntList o) {
IntIterator i = iterator();
IntIterator j = o.iterator();
while (true) {
if (i.isValid()) {
if (j.isValid()) {
if (i.value() != j.value()) {
if (i.value() < j.value())
return -1;
else
return 1;
}
} else
return 1;
} else {
if (j.isValid())
return -1;
else
return 0;
}
i.advance();
j.advance();
}
}
}
class IntArrayList extends IntList {
private int[] array;
private int size;
public IntArrayList() {
this(10);
}
public IntArrayList(int capacity) {
array = new int[capacity];
}
public IntArrayList(IntList list) {
this(list.size());
addAll(list);
}
public int get(int index) {
if (index >= size)
throw new IndexOutOfBoundsException();
return array[index];
}
public int size() {
return size;
}
public void add(int value) {
ensureCapacity(size + 1);
array[size++] = value;
}
public void ensureCapacity(int newCapacity) {
if (newCapacity > array.length) {
int[] newArray = new int[Math.max(newCapacity, array.length << 1)];
System.arraycopy(array, 0, newArray, 0, size);
array = newArray;
}
}
}
abstract class IntCollection {
public abstract IntIterator iterator();
public abstract int size();
public abstract void add(int value);
public int count(int value) {
int result = 0;
for (IntIterator iterator = iterator(); iterator.isValid(); iterator.advance()) {
if (iterator.value() == value)
result++;
}
return result;
}
public void addAll(IntCollection values) {
for (IntIterator it = values.iterator(); it.isValid(); it.advance()) {
add(it.value());
}
}
}
class IntegerUtils {
public static long power(long base, long exponent, long mod) {
if (base >= mod)
base %= mod;
if (exponent == 0)
return 1 % mod;
long result = power(base, exponent >> 1, mod);
result = result * result % mod;
if ((exponent & 1) != 0)
result = result * base % mod;
return result;
}
public static long reverse(long number, long module) {
return power(number, module - 2, module);
}
}
interface Edge {
}
interface IntIterator {
public int value() throws NoSuchElementException;
/*
* @throws NoSuchElementException only if iterator already invalid
*/
public void advance() throws NoSuchElementException;
public boolean isValid();
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 0dc59ad666e108d08fcfb2adbdb57476 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes |
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/*
10
0 0 1 2 0 5 1 2 3
1 0 0 1 0 0 1 1 0 1
δ½ΏεΎζ―δΈδΈͺθΏιεε
εͺζδΈδΈͺη½θ²η»ηΉ
θΎεΊζ ·δΎ2οΌ
f[u]葨瀺uεζ ζδΈδΈͺη½ηΉηζΉζ‘ζ°
g[u]葨瀺uεζ 沑ζη½ηΉηζΉζ‘ζ°
f[u]=f[u]*g[son]+f[u]*f[son]+g[u]*f[son]
g[u]=g[u]*g[son]+g[u]*f[son]
ιε½η»ζ’ ε¦ζε½εθηΉζ― η½θ²
*/
public class Main {
static long[] f;
static long[] g;
final static long mod = 1000000007;
public static void dfs(List[] tree,int[]color,int idx,int fd){
if(color[idx] == 1)f[idx] = 1;
else g[idx] = 1;
List<Integer> nexts = tree[idx];
for(Integer next : nexts){
if(next == fd)continue;
dfs(tree,color,next,idx);
f[idx] =(f[idx]*g[next]%mod + f[next]*f[idx]%mod + g[idx] *f[next]%mod)%mod;
g[idx] =(g[idx]*g[next]%mod + g[idx] * f[next]%mod)%mod;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Integer>[] tree = new ArrayList[n];
for (int i = 0; i <n ; i++) {
tree[i] = new ArrayList<>();
}
// θΏζ₯ ε½εθηΉ i+1εθ―»ε
₯ηfather
for (int i = 0; i <n-1 ; i++) {
int fd = sc.nextInt();
tree[fd].add(i+1);
tree[i+1].add(fd);
}
int[] color = new int[n];
f = new long[n];
g = new long[n];
// ζ―δΈͺθηΉηι’θ² 0 η½θ² 1 ι»θ²
for (int i = 0; i <n ; i++) {
color[i] = sc.nextInt();
}
dfs(tree,color,0,-1);
System.out.println(f[0]);
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 8aa4146a6aa429b864787feef5ef49a5 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.File;
import java.io.Writer;
import java.util.List;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author abra
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB extends SimpleSavingChelperSolution {
int MOD = 1000000007;
List<List<Integer>> children;
boolean[] black;
public void solve(int testNumber) {
int n = in.nextInt();
int[] parent = new int[n];
children = new ArrayList<>();
for (int i = 0; i < n; i++) {
children.add(new ArrayList<>());
}
for (int i = 1; i < n; i++) {
children.get(in.nextInt()).add(i);
}
black = new boolean[n];
for (int i = 0; i < n; i++) {
black[i] = in.nextInt() == 1;
}
long[] res = f(0);
out.println(res[0]);
}
long[] f(int v) {
long[] me = {0, 0};
if (black[v]) {
me[0] = 1;
} else {
me[1] = 1;
}
for (Integer integer : children.get(v)) {
long[] b = f(integer);
me = combine(me, b);
}
return me;
}
long[] combine(long[] a, long[] b) {
return new long[]{
(a[0] * b[0] % MOD + a[0] * b[1] % MOD + a[1] * b[0] % MOD) % MOD,
(a[1] * b[1] % MOD + a[1] * b[0] % MOD) % MOD};
}
}
abstract class SimpleSavingChelperSolution extends SavingChelperSolution {
public String processOutputPreCheck(int testNumber, String output) {
return output;
}
public String processOutputPostCheck(int testNumber, String output) {
return output;
}
}
class InputReader {
BufferedReader br;
StringTokenizer in;
public InputReader(String fileName) {
try {
br = new BufferedReader(new FileReader(fileName));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public InputReader(InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
}
boolean hasMoreTokens() {
while (in == null || !in.hasMoreTokens()) {
String s = nextLine();
if (s == null) {
return false;
}
in = new StringTokenizer(s);
}
return true;
}
public String nextString() {
return hasMoreTokens() ? in.nextToken() : null;
}
public String nextLine() {
try {
in = null; // riad legacy
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
abstract class SavingChelperSolution {
protected int testNumber;
public InputReader in;
public OutputWriter out;
private OutputWriter toFile;
private boolean local = new File("chelper.properties").exists();
public OutputWriter debug = local
? new OutputWriter(System.out)
: new OutputWriter(new OutputStream() {
@Override
public void write(int b) {
}
});
public SavingChelperSolution() {
try {
toFile = new OutputWriter("last_test_output.txt");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
public abstract void solve(int testNumber);
public abstract String processOutputPreCheck(int testNumber, String output);
public abstract String processOutputPostCheck(int testNumber, String output);
public void solve(int testNumber, InputReader in, OutputWriter out) {
this.testNumber = testNumber;
ByteArrayOutputStream substituteOutContents = new ByteArrayOutputStream();
OutputWriter substituteOut = new OutputWriter(substituteOutContents);
this.in = in;
this.out = substituteOut;
solve(testNumber);
substituteOut.flush();
String result = substituteOutContents.toString();
result = processOutputPreCheck(testNumber, result);
out.print(result);
out.flush();
if (local) {
debug.flush();
result = processOutputPostCheck(testNumber, result);
toFile.print(result);
toFile.flush();
}
}
}
class OutputWriter extends PrintWriter {
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public OutputWriter(OutputStream outputStream) {
super(outputStream);
}
public OutputWriter(Writer writer) {
super(writer);
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 2ebb0442a017998bc6f86c82d01709a8 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.List;
import java.math.BigInteger;
import java.io.OutputStream;
import java.util.Iterator;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.Arrays;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.Comparator;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
Graph graph;
long[][] dp;
int[] X;
int MOD=1_000_000_007;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n=in.readInt();
int[] parent= IOUtils.readIntArray(in, n - 1);
graph= Graph.createTree(parent);
dp=new long[n][2];
ArrayUtils.fill(dp, -1);
X=IOUtils.readIntArray(in, n);
out.printLine(dp(0, 1));
//for (int i=0; i<n; i++) out.printLine(i, dp(i, 0), dp(i, 1));
}
long dp(int u, int black) {
if (dp[u][black]!=-1) return dp[u][black];
long ret;
if (X[u]==0) {
if (black==0) {
ret = 1;
for (int i = graph.firstOutbound(u); i != -1; i = graph.nextOutbound(i)) {
int v = graph.destination(i);
ret = ret * (dp(v, 0) + dp(v, 1)) % MOD;
}
} else {
long prod = 1;
ret=0;
for (int i = graph.firstOutbound(u); i != -1; i = graph.nextOutbound(i)) {
int v = graph.destination(i);
prod = prod * (dp(v, 0) + dp(v, 1)) % MOD;
}
for (int i = graph.firstOutbound(u); i != -1; i = graph.nextOutbound(i)) {
int v = graph.destination(i);
ret=(ret+prod* IntegerUtils.reverse((dp(v, 0) + dp(v, 1)) % MOD, MOD)%MOD*dp(v, 1)%MOD)%MOD;
}
}
} else if (black==0) ret=0;
else {
ret = 1;
for (int i = graph.firstOutbound(u); i != -1; i = graph.nextOutbound(i)) {
int v = graph.destination(i);
ret = ret * (dp(v, 0) + dp(v, 1)) % MOD;
}
}
return dp[u][black]=ret;
}
}
class Graph {
public static final int REMOVED_BIT = 0;
protected int vertexCount;
protected int edgeCount;
private int[] firstOutbound;
private int[] firstInbound;
private Edge[] edges;
private int[] nextInbound;
private int[] nextOutbound;
private int[] from;
private int[] to;
private long[] weight;
public long[] capacity;
private int[] reverseEdge;
private int[] flags;
public Graph(int vertexCount, int edgeCapacity) {
this.vertexCount = vertexCount;
firstOutbound = new int[vertexCount];
Arrays.fill(firstOutbound, -1);
from = new int[edgeCapacity];
to = new int[edgeCapacity];
nextOutbound = new int[edgeCapacity];
flags = new int[edgeCapacity];
}
public static Graph createTree(int[] parent) {
Graph graph = new Graph(parent.length + 1, parent.length);
for (int i = 0; i < parent.length; i++)
graph.addSimpleEdge(parent[i], i + 1);
return graph;
}
public int addEdge(int fromID, int toID, long weight, long capacity, int reverseEdge) {
ensureEdgeCapacity(edgeCount + 1);
if (firstOutbound[fromID] != -1)
nextOutbound[edgeCount] = firstOutbound[fromID];
else
nextOutbound[edgeCount] = -1;
firstOutbound[fromID] = edgeCount;
if (firstInbound != null) {
if (firstInbound[toID] != -1)
nextInbound[edgeCount] = firstInbound[toID];
else
nextInbound[edgeCount] = -1;
firstInbound[toID] = edgeCount;
}
this.from[edgeCount] = fromID;
this.to[edgeCount] = toID;
if (capacity != 0) {
if (this.capacity == null)
this.capacity = new long[from.length];
this.capacity[edgeCount] = capacity;
}
if (weight != 0) {
if (this.weight == null)
this.weight = new long[from.length];
this.weight[edgeCount] = weight;
}
if (reverseEdge != -1) {
if (this.reverseEdge == null) {
this.reverseEdge = new int[from.length];
Arrays.fill(this.reverseEdge, 0, edgeCount, -1);
}
this.reverseEdge[edgeCount] = reverseEdge;
}
if (edges != null)
edges[edgeCount] = createEdge(edgeCount);
return edgeCount++;
}
protected final GraphEdge createEdge(int id) {
return new GraphEdge(id);
}
public final int addFlowWeightedEdge(int from, int to, long weight, long capacity) {
if (capacity == 0) {
return addEdge(from, to, weight, 0, -1);
} else {
int lastEdgeCount = edgeCount;
addEdge(to, from, -weight, 0, lastEdgeCount + entriesPerEdge());
return addEdge(from, to, weight, capacity, lastEdgeCount);
}
}
protected int entriesPerEdge() {
return 1;
}
public final int addWeightedEdge(int from, int to, long weight) {
return addFlowWeightedEdge(from, to, weight, 0);
}
public final int addSimpleEdge(int from, int to) {
return addWeightedEdge(from, to, 0);
}
public final int firstOutbound(int vertex) {
int id = firstOutbound[vertex];
while (id != -1 && isRemoved(id))
id = nextOutbound[id];
return id;
}
public final int nextOutbound(int id) {
id = nextOutbound[id];
while (id != -1 && isRemoved(id))
id = nextOutbound[id];
return id;
}
public final int destination(int id) {
return to[id];
}
public final boolean flag(int id, int bit) {
return (flags[id] >> bit & 1) != 0;
}
public final boolean isRemoved(int id) {
return flag(id, REMOVED_BIT);
}
protected void ensureEdgeCapacity(int size) {
if (from.length < size) {
int newSize = Math.max(size, 2 * from.length);
if (edges != null)
edges = resize(edges, newSize);
from = resize(from, newSize);
to = resize(to, newSize);
nextOutbound = resize(nextOutbound, newSize);
if (nextInbound != null)
nextInbound = resize(nextInbound, newSize);
if (weight != null)
weight = resize(weight, newSize);
if (capacity != null)
capacity = resize(capacity, newSize);
if (reverseEdge != null)
reverseEdge = resize(reverseEdge, newSize);
flags = resize(flags, newSize);
}
}
protected final int[] resize(int[] array, int size) {
int[] newArray = new int[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private long[] resize(long[] array, int size) {
long[] newArray = new long[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private Edge[] resize(Edge[] array, int size) {
Edge[] newArray = new Edge[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
protected class GraphEdge implements Edge {
protected int id;
protected GraphEdge(int id) {
this.id = id;
}
}
}
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 isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public void close() {
writer.close();
}
public void printLine(long i) {
writer.println(i);
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
}
class ArrayUtils {
public static void fill(long[][] array, long value) {
for (long[] row : array)
Arrays.fill(row, value);
}
}
class IntegerUtils {
public static long power(long base, long exponent, long mod) {
if (base >= mod)
base %= mod;
if (exponent == 0)
return 1 % mod;
long result = power(base, exponent >> 1, mod);
result = result * result % mod;
if ((exponent & 1) != 0)
result = result * base % mod;
return result;
}
public static long reverse(long number, long module) {
return power(number, module - 2, module);
}
}
interface Edge {
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 0d6c810bf5723fa980e90a29755c2fbb | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.util.*;
import java.io.*;
@SuppressWarnings("unchecked")
public class applemantree {
final int MOD = 1000000007;
int N;
boolean[] coloredBlack;
int[] dpWhite, dpBlack;
ArrayList<Integer>[] children;
applemantree(BufferedReader in, PrintWriter out) throws IOException {
StringTokenizer st = new StringTokenizer(in.readLine());
N = Integer.parseInt(st.nextToken());
children = new ArrayList[N];
for (int i = 0; i < N; i++) children[i] = new ArrayList<>(2);
st = new StringTokenizer(in.readLine());
for (int i = 1; i < N; i++) children[Integer.parseInt(st.nextToken())].add(i);
coloredBlack = new boolean[N];
st = new StringTokenizer(in.readLine());
for (int i = 0; i < N; i++) coloredBlack[i] = (Integer.parseInt(st.nextToken()) == 1);
dpWhite = new int[N];
dpBlack = new int[N];
go(0);
// System.out.println(Arrays.toString(dpWhite));
// System.out.println(Arrays.toString(dpBlack));
out.println(dpBlack[0]);
}
void go(int n) {
for (int e : children[n]) go(e);
if (coloredBlack[n]) {
// All children must cut off black vertexes or extend current subtrees
long result = 1;
for (int e : children[n]) result = result * (dpBlack[e] + dpWhite[e]) % MOD;
dpBlack[n] = (int) result;
// No way to make subtree have no black nodes (this node itself is black)
dpWhite[n] = 0;
} else {
// All children must cut off black vertexes for dpWhite, or extend their
// current subtree
long multWhite = 1;
for (int e : children[n]) {
multWhite = multWhite * (dpBlack[e] + dpWhite[e]) % MOD;
}
dpWhite[n] = (int) multWhite;
// Exactly one child must extend black vertex for dpBlack
long blackResult = 0;
for (int e : children[n]) {
blackResult += (long) moddiv((int) multWhite, (dpBlack[e] + dpWhite[e]) % MOD) * dpBlack[e] % MOD;
blackResult %= MOD;
}
dpBlack[n] = (int) blackResult;
}
}
int moddiv(int a, int b) {
int inv;
if (b == 1) inv = 1;
else inv = modinv(MOD, b).b;
return (int) ((long) a * inv % MOD);
}
Pair modinv(int a, int b) {
int c = a / b;
int d = a % b;
if (d == 1) {
// Base case
return new Pair(1, -c + MOD);
} else {
Pair pair = modinv(b, d);
int e = pair.a;
int f = pair.b;
int nf = (int) (((long) -c * f + e) % MOD);
if (nf < 0) nf += MOD;
return new Pair(f, nf);
}
}
static class Pair {
int a, b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public String toString() {
return "(" + a + ", " + b + ")";
}
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
new applemantree(in, out);
in.close();
out.close();
}
} | Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | aa3b2aa737a6a6e8f3bace9dbecf9b79 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static PrintWriter out;
static Reader in;
public static void main(String[] args) throws IOException {
//out = new PrintWriter(new File("out.txt"));
//PrintWriter out = new PrintWriter(System.out);
//in = new Reader(new FileInputStream("in.txt"));
//Reader in = new Reader();
input_output();
Main solver = new Main();
solver.solve();
out.flush();
out.close();
}
static int INF = (int)2e9+5;
static int maxn = (int)2e6+5;
static int mod=(int)1e9+7 ;
static int n, m, t, q, k;
// read the editorial of the last problem (K).
static ArrayList<Integer> adj[];
static int[] color;
static long ans, dp[][];
void solve() throws IOException{
n = in.nextInt();
adj = new ArrayList[n+1];
for (int i = 1; i <= n ;i++) adj[i] = new ArrayList<Integer>();
int u, v;
for (int i = 2; i <= n; i++) {
u = i;
v = in.nextInt()+1;
adj[u].add(v);
adj[v].add(u);
}
color = new int[n+1];
int start = 0;
for (int i = 1; i <= n; i++) {
color[i] = in.nextInt();
}
dp = new long[n+1][2];
DFS(1, 0);
out.println(dp[1][1]);
}
//<>
static void DFS(int s, int p) {
if (color[s] == 0) {
dp[s][0] = 1;
dp[s][1] = 0;
} else {
dp[s][1] = 1;
dp[s][0] = 0;
}
for (int e: adj[s]) {
if (e == p) continue;
DFS(e, s);
dp[s][1] = ((dp[s][1]*(dp[e][0]+dp[e][1]))%mod+(dp[s][0]*dp[e][1])%mod)%mod;
dp[s][0] = (dp[s][0]*(dp[e][0]+dp[e][1]))%mod;
}
}
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public Reader() {
this(System.in);
}
public Reader(InputStream is) {
mIs = is;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = mIs.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String 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();
}
double nextDouble()
{
return Double.parseDouble(next());
}
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 int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
static void input_output() throws IOException {
File f = new File("in.txt");
if(f.exists() && !f.isDirectory()) {
in = new Reader(new FileInputStream("in.txt"));
} else in = new Reader();
f = new File("out.txt");
if(f.exists() && !f.isDirectory()) {
out = new PrintWriter(new File("out.txt"));
} else out = new PrintWriter(System.out);
}
} | Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | a7f9a9752c77e988d72d593440ec12cd | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.util.*;
import java.io.*;
public class EdE {
static long[][] dp;
static Map<Integer, ArrayList<Integer>> mp;
static long num = 1000000007;
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
mp = new HashMap<Integer, ArrayList<Integer>>();
int n = Integer.parseInt(bf.readLine());
for(int j = 0;j<n;j++)
mp.put(j, new ArrayList<Integer>());
StringTokenizer st = new StringTokenizer(bf.readLine());
for(int j =0 ;j<n-1;j++){
int v = Integer.parseInt(st.nextToken());
mp.get(j+1).add(v);
mp.get(v).add(j+1);
}
dp = new long[n][2]; // [0] means there is 0 black nodes in the subtree that includes that node, [1] means ther eis 1 black node in the subtree that includes that node
StringTokenizer st1 = new StringTokenizer(bf.readLine());
for(int j =0 ;j<n;j++){
int bw = Integer.parseInt(st1.nextToken());
dp[j][0] = 1-bw;
dp[j][1] = bw;
}
dfs(0, -1);
out.println(dp[0][1]);
out.close();
}
public static void dfs(int v, int p){
for(int child : mp.get(v)){
if (child == p)
continue;
dfs(child, v);
long zero = 0;
long one = 0;
zero+=dp[v][0]*dp[child][0];
zero%=num;
one+=dp[v][1]*dp[child][0];
one%=num;
one+=dp[v][0]*dp[child][1];
one%=num;
zero+=dp[v][0]*dp[child][1];
zero%=num;
one+=dp[v][1]*dp[child][1];
one%=num;
dp[v][0] = zero;
dp[v][1] = one;
}
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 7f8abfa64ae95b1e1d06015bb1433320 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | /**
* Created by Aminul on 8/14/2018.
*/
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class CF461B {
public static void main(String[] args)throws Exception {
FastReader in = new FastReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = in.nextInt();
dp = new long[2][n];
color = new int[n];
g = genList(n);
for (int i = 1; i <= n-1; i++) {
int u = in.nextInt(), v = i;
g[u].add(v); g[v].add(u);
}
for (int i = 0; i < n; i++) {
color[i] = in.nextInt();
}
int root = 0;
dfs(root, -1);
pw.println(dp[1][root]);
pw.close();
}
static List<Integer> g[];
static int color[];
static long dp[][], mod = (long)1e9+7;
static void dfs(int u, int p){
dp[0][u] = 1;
for(int v : g[u]){
if(v == p) continue;
dfs(v, u);
dp[1][u] = (dp[0][u] * dp[1][v] + dp[1][u] * dp[0][v]) % mod;
dp[0][u] = (dp[0][u] * dp[0][v]) % mod;
}
if(color[u] == 1) {
dp[1][u] = dp[0][u];
}
else{
dp[0][u] = (dp[0][u] + dp[1][u]) % mod;
}
}
static <T>List<T>[] genList(int n){
List<T> list[] = new List[n];
for(int i = 0; i < n; i++) list[i] = new ArrayList<T>();
return list;
}
static void debug(Object...obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
static final int ints[] = new int[128];
public FastReader(InputStream is){
for(int i='0';i<='9';i++) ints[i]=i-'0';
this.is = is;
}
public 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++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() {
int b;
while((b = readByte()) != -1 && isSpaceChar(b));
return b;
}
public String next(){
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int nextInt(){
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<<3) + (num<<1) + ints[b];
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
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<<3) + (num<<1) + ints[b];
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
/* public char nextChar() {
return (char)skip();
}*/
public char[] next(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 buff[] = new char[1005];
public char[] nextCharArray(){
int b = skip(), p = 0;
while(!(isSpaceChar(b))){
buff[p++] = (char)b;
b = readByte();
}
return Arrays.copyOf(buff, p);
}*/
}
} | Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 294bab0b2b00f728173c75e98001ce72 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | /* / οΎοΎβ β β β β β β β β β β β γ
/ )\β β β β β β β β β β β β Y
(β β | ( Ν‘Β° ΝΚ Ν‘Β°οΌβ β(β γ
(β οΎβ Y βγ½-γ __οΌ
| _β qγ| γq |/
(β γΌ '_δΊΊ`γΌ οΎ
β |\ οΏ£ _δΊΊ'彑οΎ
β )\β β qβ β /
β β (\β #β /
β /β β β /α½£====================D-
/β β β /β \ \β β \
( (β )β β β β ) ).β )
(β β )β β β β β ( | /
|β /β β β β β β | /
[_] β β β β β [___] */
// Main Code at the Bottom
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
//Fast IO class
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
boolean env=System.getProperty("ONLINE_JUDGE") != null;
if(!env) {
try {
br=new BufferedReader(new FileReader("src\\input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long MOD=1000000000+7;
//Euclidean Algorithm
static long gcd(long A,long B){
return (B==0)?A:gcd(B,A%B);
}
//Modular Exponentiation
static long fastExpo(long x,long n){
if(n==0) return 1;
if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD;
return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD;
}
//Modular Inverse
static long inverse(long x) {
return fastExpo(x,MOD-2);
}
//Prime Number Algorithm
static boolean isPrime(long n){
if(n<=1) return false;
if(n<=3) return true;
if(n%2==0 || n%3==0) return false;
for(int i=5;i*i<=n;i+=6) if(n%i==0 || n%(i+2)==0) return false;
return true;
}
//Reverse an array
static void reverse(int arr[],int l,int r){
while(l<r) {
int tmp=arr[l];
arr[l++]=arr[r];
arr[r--]=tmp;
}
}
//Print array
static void print1d(int arr[]) {
out.println(Arrays.toString(arr));
}
static void print2d(int arr[][]) {
for(int a[]: arr) out.println(Arrays.toString(a));
}
// Pair
static class pair{
int x,y;
pair(int a,int b){
this.x=a;
this.y=b;
}
public boolean equals(Object obj) {
if(obj == null || obj.getClass()!= this.getClass()) return false;
pair p = (pair) obj;
return (this.x==p.x && this.y==p.y);
}
public int hashCode() {
return Objects.hash(x,y);
}
}
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
//Main function(The main code starts from here
static int V,color[];
static long dp[][];
static ArrayList<Integer> graph[];
static void init(int n){
V=n;
dp=new long[n][2];
color=new int[n];
graph=new ArrayList[V];
for(int i=0;i<V;i++) graph[i]=new ArrayList<>();
}
static void addEdge(int src,int dest){
graph[src].add(dest);
graph[dest].add(src);
}
static long add(long a,long b) {
return (a%MOD+b%MOD)%MOD;
}
static long mult(long a,long b) {
return ((a%MOD)*(b%MOD))%MOD;
}
static long div(long a,long b) {
return ((a%MOD)*(inverse(b)%MOD))%MOD;
}
static void dfs(int s,int p) {
if(color[s]==1) {
dp[s][1]=1;
for(Integer x: graph[s]) {
if(x==p) continue;
dfs(x,s);
dp[s][1]=mult(dp[s][1],add(dp[x][0],dp[x][1]));
}
}
else {
dp[s][0]=1;
for(Integer x: graph[s]) {
if(x==p) continue;
dfs(x,s);
dp[s][0]=mult(dp[s][0],add(dp[x][0],dp[x][1]));
}
for(Integer x: graph[s]) {
if(x==p) continue;
dp[s][1]=add(dp[s][1],mult(dp[x][1],div(dp[s][0],add(dp[x][1],dp[x][0]))));
}
}
}
public static void main (String[] args) throws java.lang.Exception {
int test;
test=1;
//test=sc.nextInt();
while(test-->0){
int n=sc.nextInt();
init(n);
for(int i=0;i<n-1;i++) addEdge(i+1,sc.nextInt());
for(int i=0;i<n;i++) color[i]=sc.nextInt();
dfs(0,-1);
out.println(dp[0][1]%MOD);
}
out.flush();
out.close();
}
} | Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 4f9230af62af04cdaa5b4d7f14cab2d6 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author zodiacLeo
*/
public class Main
{
public static void main(String[] args)
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD
{
private int V;
private long[] color;
private long[][] dp;
private ArrayList<Integer>[] g;
private final static long MOD = (int) 1e9 + 7;
public void solve(int testNumber, FastScanner in, FastPrinter out)
{
V = in.nextInt();
g = new ArrayList[V];
color = new long[V];
dp = new long[V][2];
for (int i = 0; i < V; i++)
{
g[i] = new ArrayList<Integer>();
}
for (int i = 1; i < V; i++)
{
int from = i;
int to = in.nextInt();
g[from].add(to);
g[to].add(from);
}
for (int i = 0; i < V; i++)
{
color[i] = in.nextLong();
}
dfs(0, -1);
out.println(dp[0][1]);
}
public void dfs(int v, int parent)
{
if (color[v] == 1)
{
dp[v][0] = 0;
dp[v][1] = 1;
} else
{
dp[v][0] = 1;
dp[v][1] = 0;
}
for (int i = 0; i < g[v].size(); i++)
{
int u = g[v].get(i);
if (u != parent)
{
long value1 = dp[v][0];
long value2 = dp[v][1];
dp[v][0] = dp[v][1] = 0;
dfs(u, v);
//U is included with the subtree rooted at V//
dp[v][0] += (value1 * dp[u][0]) % MOD;
dp[v][0] %= MOD;
dp[v][1] += (value2 * dp[u][0]) % MOD;
dp[v][1] %= MOD;
dp[v][1] += (value1 * dp[u][1]) % MOD;
dp[v][1] %= MOD;
//U is not included with the subtree rooted at V//
dp[v][0] += (value1 * dp[u][1]) % MOD;
dp[v][0] %= MOD;
dp[v][1] += (value2 * dp[u][1]) % MOD;
dp[v][1] %= MOD;
}
}
}
}
static class FastScanner
{
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream is)
{
br = new BufferedReader(new InputStreamReader(is));
}
public FastScanner(File f)
{
try
{
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public String next()
{
while (st == null || !st.hasMoreElements())
{
String s = null;
try
{
s = br.readLine();
} catch (IOException e)
{
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
static class FastPrinter extends PrintWriter
{
public FastPrinter(OutputStream out)
{
super(out);
}
public FastPrinter(Writer out)
{
super(out);
}
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 8f7f88ce941a488b392396c79f4b8a72 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Main {
int mod = 1000000007;
public class SegmentTree{
int n;
int[] tree;
SegmentTree(int[] arr){
this.n = arr.length;
this.tree = new int[2 * n];
for(int i = n; i < 2 * n; i++){
this.tree[i] = arr[i - n];
}
for(int i = n - 1; i >= 1; i--){
this.tree[i] = Math.min(this.tree[2 * i], this.tree[2 * i + 1]);
}
}
public int query(int l, int r){
int res = Integer.MAX_VALUE;
l = l + n;
r = r + n;
while(l < r){
if(l % 2 == 1){
res = Math.min(res, tree[l]);
l++;
}
if(r % 2 == 1){
r--;
res = Math.min(res, tree[r]);
}
l /= 2;
r /= 2;
}
return res;
}
}
int n;
HashMap<Integer, List<Integer>> map = new HashMap<>();
int[] color;
long[][] dp;
public void solve() throws IOException{
n = in.nextInt();
dp = new long[n][2];
for(int i = 0; i <= n - 1; i++){
map.put(i, new ArrayList<>());
}
for(int i = 0; i < n - 1; i++){
int p = in.nextInt();
map.get(i + 1).add(p);
map.get(p).add(i + 1);
}
color = new int[n];
for(int i = 0; i < n; i++){
color[i] = in.nextInt();
}
dfs(0, -1);
out.println(dp[0][1]);
}
public void dfs(int u, int prev){
dp[u][0] = 1 - color[u];
dp[u][1] = color[u];
for(int v : map.get(u)){
if(v == prev)
continue;
dfs(v, u);
long c0 = dp[u][0];
long c1 = dp[u][1];
dp[u][0] = dp[u][1] = 0;
// if u, v are not connectioned
dp[u][0] = (dp[u][0] + (c0 * dp[v][1]) % mod) % mod;
dp[u][1] = (dp[u][1] + (c1 * dp[v][1]) % mod) % mod;
// if u and v are connected;
dp[u][1] = (dp[u][1] + (c0 * dp[v][1]) % mod) % mod;
dp[u][1] = (dp[u][1] + (c1 * dp[v][0]) % mod) % mod;
dp[u][0] = (dp[u][0] + (c0 * dp[v][0]) % mod) % mod;
}
}
FastScanner in;
PrintWriter out;
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = null;
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
if (st == null || !st.hasMoreTokens())
return br.readLine();
StringBuilder result = new StringBuilder(st.nextToken());
while (st.hasMoreTokens()) {
result.append(" ");
result.append(st.nextToken());
}
return result.toString();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
void run() throws IOException {
in = new FastScanner(System.in);
out = new PrintWriter(System.out, false);
solve();
out.close();
}
public static void main(String[] args) throws IOException{
new Main().run();
}
public void printArr(int[] arr){
for(int i = 0; i < arr.length; i++){
out.print(arr[i] + " ");
}
out.println();
}
public long gcd(long a, long b){
if(a == 0) return b;
return gcd(b % a, a);
}
public boolean isPrime(long num){
if(num == 0 || num == 1){
return false;
}
for(int i = 2; i * i <= num; i++){
if(num % i == 0){
return false;
}
}
return true;
}
public class Pair<A, B>{
public A x;
public B y;
Pair(A x, B y){
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
if (!x.equals(pair.x)) return false;
return y.equals(pair.y);
}
@Override
public int hashCode() {
int result = x.hashCode();
result = 31 * result + y.hashCode();
return result;
}
}
class Tuple{
int x; int y; int z;
Tuple(int ix, int iy, int iz){
x = ix;
y = iy;
z = iz;
}
}
}
| Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 46c9bf7fa5a14ff88727489b20ea98f0 | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes | import java.util.*;
import java.io.*;
public class tr0 {
static PrintWriter out;
static StringBuilder sb;
static int mod = 1000000007;
static long inf = (long) 1e18 + 1;
static int[] col;
static int n;
static ArrayList<Integer>[] ad;
static long[][] memo;
static HashSet<Integer> h;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
n = sc.nextInt();
ad = new ArrayList[n];
for (int i = 0; i < n; i++)
ad[i] = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int x = sc.nextInt();
ad[x].add(i + 1);
ad[i + 1].add(x);
}
col = new int[n];
int st = 0;
for (int i = 0; i < n; i++) {
col[i] = sc.nextInt();
if (col[i] == 1)
st = i;
}
memo = new long[n][2];
for (long[] a : memo)
Arrays.fill(a, -1);
dfs(0, -1);
out.println(memo[0][1]);
out.flush();
}
static void dfs(int u, int p) {
if (col[u] == 1) {
memo[u][0] = 0;
memo[u][1] = 1;
} else {
memo[u][0] = 1;
memo[u][1] = 0;
}
for (int v : ad[u])
if (v != p) {
dfs(v, u);
memo[u][1] = (memo[u][1] * (memo[v][0] + memo[v][1]) % mod)+memo[u][0]*memo[v][1];
memo[u][0] = memo[u][0] * (memo[v][0] + memo[v][1]) % mod;
memo[u][1] %= mod;
memo[u][0] %= mod;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] nextArrInt(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextArrLong(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["3\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | d8e0fdb9d6621824eb14422757747e1d | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
final int MD = 1000_000_007;
int[] a, next, last, color;
long [] f, deg, f1;
int k;
boolean[] banned, used;
void add(int x, int y) {
k++;
next[k] = last[x];
last[x] = k;
a[k] = y;
}
int[] d;
long pow(long a, long b) {
if (b == 0) return 1;
if (b % 2 == 1) return pow(a, b - 1) * a % MD;
a = a * a % MD;
return pow(a, b / 2);
}
void dfs(int v, int p) {
used[v] = true;
int j = last[v];
long prod = 1;
while (j > 0) {
if (a[j] == p) {
j = next[j];
continue;
}
dfs(a[j], v);
prod = (prod * ((f[a[j]] + f1[a[j]]) % MD)) % MD;
j = next[j];
}
f[v] = prod;
if (color[v] == 1) {
f1[v] = prod;
f[v] = 0;
return;
}
j = last[v];
while (j > 0) {
if (a[j] == p) {
j = next[j];
continue;
}
f1[v] = (f1[v] + ((f[v] * f1[a[j]]) % MD) * pow((f[a[j]] + f1[a[j]]) % MD, MD - 2)) % MD;
j = next[j];
}
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
k = 0;
a = new int[n * 2 + 1];
next = new int[n * 2 + 1];
last = new int[n + 1];
f = new long[n + 1];
deg = new long[n + 1];
color = new int[n + 1];
d = new int[n + 1];
deg[0] = 1;
banned = new boolean[n + 1];
used = new boolean[n + 1];
f1 = new long[n + 1];
for (int i = 1; i <= n; i++) {
deg[i] = deg[i - 1] + deg[i - 1];
if (deg[i] >= MD) deg[i] -= MD;
}
for (int i = 0; i < n - 1; i++) {
int p = in.nextInt();
add(i + 1, p);
add(p, i + 1);
d[i + 1]++;
d[p]++;
}
for (int i = 0; i < n; i++) {
color[i] = in.nextInt();
}
dfs(0, -1);
out.println(f1[0]);
}
}
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\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output | |
PASSED | 05f0f7ce79d4b6e8c488502f86584ddf | train_004.jsonl | 1409061600 | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.Consider a set consisting of k (0ββ€βkβ<βn) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (kβ+β1) parts. Note, that each part will be a tree with colored vertices.Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109β+β7). | 256 megabytes |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* 4 4
* 1 5 3 4
* 1 2
* 1 3
* 2 3
* 3 3
*
*
* @author pttrung
*/
public class A {
public static long Mod = (long) (1e9 + 7);
public static long[][] dp;
public static void main(String[] args) throws FileNotFoundException {
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
ArrayList<Integer>[] map = new ArrayList[n];
for (int i = 0; i < n; i++) {
map[i] = new ArrayList();
}
for (int i = 0; i < n - 1; i++) {
int v = in.nextInt();
map[i + 1].add(v);
map[v].add(i + 1);
}
int[] black = new int[n];
for (int i = 0; i < n; i++) {
black[i] = in.nextInt();
}
dp = new long[n][2];
dfs(0,0,map,black);
out.println(dp[0][1]);
out.close();
}
public static void dfs(int n, int pa, ArrayList<Integer>[] map, int[] black) {
dp[n][0] = 1 - black[n];
dp[n][1] = black[n];
for (int i : map[n]) {
if (i != pa) {
long a = dp[n][0];
long b = dp[n][1];
dp[n][0] = 0;
dp[n][1] = 0;
dfs(i, n, map, black);
dp[n][0] += a * dp[i][1];
dp[n][0] %= Mod;
dp[n][1] += b * dp[i][1];
dp[n][1] %= Mod;
dp[n][1] += b * dp[i][0];
dp[n][1] %= Mod;
dp[n][1] += a * dp[i][1];
dp[n][1] %= Mod;
dp[n][0] += a * dp[i][0];
dp[n][0] %= Mod;
}
}
}
public static long pow(int a, int b, long mod) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long v = pow(a, b / 2, mod);
if (b % 2 == 0) {
return (v * v) % mod;
} else {
return (((v * v) % mod) * a) % mod;
}
}
public static int[][] powSquareMatrix(int[][] A, long p) {
int[][] unit = new int[A.length][A.length];
for (int i = 0; i < unit.length; i++) {
unit[i][i] = 1;
}
if (p == 0) {
return unit;
}
int[][] val = powSquareMatrix(A, p / 2);
if (p % 2 == 0) {
return mulMatrix(val, val);
} else {
return mulMatrix(A, mulMatrix(val, val));
}
}
public static int[][] mulMatrix(int[][] A, int[][] B) {
int[][] result = new int[A.length][B[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
long temp = 0;
for (int k = 0; k < A[0].length; k++) {
temp += ((long) A[i][k] * B[k][j] % Mod);
temp %= Mod;
}
temp %= Mod;
result[i][j] = (int) temp;
}
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
static class FT {
int[] data;
FT(int n) {
data = new int[n];
}
void update(int index, int val) {
// System.out.println("UPDATE INDEX " + index);
while (index < data.length) {
data[index] += val;
index += index & (-index);
// System.out.println("NEXT " +index);
}
}
int get(int index) {
// System.out.println("GET INDEX " + index);
int result = 0;
while (index > 0) {
result += data[index];
index -= index & (-index);
// System.out.println("BACK " + index);
}
return result;
}
}
static long gcd(long a, long b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
static long pow(long a, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val % Mod;
} else {
return (val * val % Mod) * a % Mod;
}
}
// static Point intersect(Point a, Point b, Point c) {
// double D = cross(a, b);
// if (D != 0) {
// return new Point(cross(c, b) / D, cross(a, c) / D);
// }
// return null;
// }
//
// static Point convert(Point a, double angle) {
// double x = a.x * cos(angle) - a.y * sin(angle);
// double y = a.x * sin(angle) + a.y * cos(angle);
// return new Point(x, y);
// }
static Point minus(Point a, Point b) {
return new Point(a.x - b.x, a.y - b.y);
}
//
// static Point add(Point a, Point b) {
// return new Point(a.x + b.x, a.y + b.y);
// }
//
/**
* Cross product ab*ac
*
* @param a
* @param b
* @param c
* @return
*/
static double cross(Point a, Point b, Point c) {
Point ab = new Point(b.x - a.x, b.y - a.y);
Point ac = new Point(c.x - a.x, c.y - a.y);
return cross(ab, ac);
}
static double cross(Point a, Point b) {
return a.x * b.y - a.y * b.x;
}
/**
* Dot product ab*ac;
*
* @param a
* @param b
* @param c
* @return
*/
static long dot(Point a, Point b, Point c) {
Point ab = new Point(b.x - a.x, b.y - a.y);
Point ac = new Point(c.x - a.x, c.y - a.y);
return dot(ab, ac);
}
static long dot(Point a, Point b) {
long total = a.x * b.x;
total += a.y * b.y;
return total;
}
static double dist(Point a, Point b) {
long total = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
return Math.sqrt(total);
}
static long norm(Point a) {
long result = a.x * a.x;
result += a.y * a.y;
return result;
}
static double dist(Point a, Point b, Point x, boolean isSegment) {
double dist = cross(a, b, x) / dist(a, b);
// System.out.println("DIST " + dist);
if (isSegment) {
Point ab = new Point(b.x - a.x, b.y - a.y);
long dot1 = dot(a, b, x);
long norm = norm(ab);
double u = (double) dot1 / norm;
if (u < 0) {
return dist(a, x);
}
if (u > 1) {
return dist(b, x);
}
}
return Math.abs(dist);
}
static class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
//System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new FileReader(new File("A-large (2).in")));
}
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\n0 0\n0 1 1", "6\n0 1 1 0 4\n1 1 0 0 1 0", "10\n0 1 2 1 4 4 4 0 8\n0 0 0 1 0 1 1 0 0 1"] | 2 seconds | ["2", "1", "27"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | e571191fadf6b0b26bd2f16295f32077 | The first line contains an integer n (2βββ€βnββ€β105) β the number of tree vertices. The second line contains the description of the tree: nβ-β1 integers p0,βp1,β...,βpnβ-β2 (0ββ€βpiββ€βi). Where pi means that there is an edge connecting vertex (iβ+β1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to nβ-β1. The third line contains the description of the colors of the vertices: n integers x0,βx1,β...,βxnβ-β1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. | 2,000 | Output a single integer β the number of ways to split the tree modulo 1000000007 (109β+β7). | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.