-
Notifications
You must be signed in to change notification settings - Fork 5
/
FaceTheRightWay.java
121 lines (98 loc) · 2.96 KB
/
FaceTheRightWay.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package coding.POJ.ID_3276;
/*
* FaceTheRightWay.java
*
* Version:
* $1.0$
*
* Revisions:
* $1.0$
*/
import coding.POJ.POJMain;
import com.fengkeyleaf.io.ProcessingFile;
import com.fengkeyleaf.io.ReadFromStdOrFile;
import java.util.Arrays;
import java.util.Scanner;
/**
* Face The Right Way
* @see <a href=http://poj.org/problem?id=3276>Face The Right Way</a>
*
* @author Xiaoyu Tongyang, or call me sora for short
* @see <a href="https://fengkeyleaf.com">person website</a>
*/
public final class FaceTheRightWay implements ProcessingFile {
private static final String FORWARD = "F";
private int[] cows;
private int[] flips;
public FaceTheRightWay( String fileName ) {
ReadFromStdOrFile.readFromFile( fileName, this );
doTheAlgorithm();
}
@Override
public void processingFile( Scanner sc ) {
boolean isReadLength = true;
int index = 0;
while ( sc.hasNext() ) {
String content = sc.nextLine();
// skip comments
if ( ReadFromStdOrFile.skipInputData(
content, false ) )
continue;
if ( isReadLength ) {
isReadLength = false;
cows = new int[ Integer.parseInt( content ) ];
flips = new int[ cows.length ];
continue;
}
cows[ index++ ] = content.equals( FORWARD ) ? 0 : 1;
}
}
private boolean isFlip( int i, int sum ) {
return ( cows[ i ] + sum ) % 2 != 0;
}
private int remove( int i, int K ) {
if ( i - K + 1 >= 0 )
return flips[ i - K + 1 ];
return 0;
}
private int doTheAlgorithm( int K ) {
int res = 0;
int sumPre = 0;
// ∑f[ j ] = ∑f[j] + f[i] + f[i-K+1]
for ( int i = 0; i + K <= cows.length; i++ ) {
// ∑f[ j ] % 2 != 0,
// i-th cow's direction is different from
// the initializing one's
if ( isFlip( i, sumPre ) ) {
res++;
flips[ i ] = 1;
}
// f[ i ]
sumPre += flips[ i ];
// f[ i - K + 1 ]
sumPre -= remove( i, K );
}
for ( int i = cows.length - K + 1; i < cows.length; i++ ) {
if ( isFlip( i, sumPre ) ) return -1;
sumPre -= remove( i, K );
}
return res;
}
private void doTheAlgorithm() {
int K = 1, M = cows.length;
for ( int k = 1; k <= cows.length; k++ ) {
int res = doTheAlgorithm( k );
if ( res > -1 && M > res ){
M = res;
K = k;
}
Arrays.fill( flips, 0 );
}
System.out.println( K + " " + M );
}
public static
void main( String[] args ) {
new FaceTheRightWay( POJMain.getFilePathPOJ( 3276, 1 ) ); // 3 3
// new FaceTheRightWay( ReadFromStdOrFile.getFilePathPOJ( 3276, 2 ) ); // 1 0
}
}