Sunday, April 16, 2017

Codeforces Round #409 (rated, Div. 2, based on VK Cup 2017 Round 2) A -- D

http://codeforces.com/
A. Vicious Keyboard
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Tonio has a keyboard with only two letters, "V" and "K".
One day, he has typed out a string s with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximum number of times "VK" can appear as a substring (i. e. a letter "K" right after a letter "V") in the resulting string.
Input
The first line will contain a string s consisting only of uppercase English letters "V" and "K" with length not less than 1 and not greater than 100.
Output
Output a single integer, the maximum number of times "VK" can appear as a substring of the given string after changing at most one character.
Examples
input
VK
output
1
input
VV
output
1
input
V
output
0
input
VKKKKKKKKKVVVVVVVVVK
output
3
input
KVKV
output
1
Note
For the first case, we do not change any letters. "VK" appears once, which is the maximum number of times it could appear.
For the second case, we can change the second character from a "V" to a "K". This will give us the string "VK". This has one occurrence of the string "VK" as a substring.
For the fourth case, we can change the fourth character from a "K" to a "V". This will give us the string "VKKVKKKKKKVVVVVVVVVK". This has three occurrences of the string "VK" as a substring. We can check no other moves can give us strictly more occurrences.

solution:
1. Find the number of all available "VK"s and mark all "VK"s. (ans)
2. Search the string to see if there is two adjacent 'V's or 'K's that are not marked yet . If so, ans++.
code:
#include <bits/stdc++.h>
using namespace std;
int v, k, ans;
int vis[105];
string s;
int main(){
 cin >> s;
 for(int i = 0 ; i < s.size() - 1; i++){
  if(s[i] == 'V' && s[i + 1] == 'K'){
   vis[i] = 1;
   vis[i + 1] = 1;
   ans++;
  }
 }
 for(int i = 0; i < s.size() - 1; i++){
  if(!vis[i] && !vis[i + 1]){
   if(s[i] == s[i + 1]){
    ans++;
    break;
   }
  }
 }
 printf("%d\n", ans);
return 0;
}


B. Valued Keys
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You found a mysterious function f. The function takes two strings s1 and s2. These strings must consist only of lowercase English letters, and must be the same length.
The output of the function f is another string of the same length. The i-th character of the output is equal to the minimum of the i-th character of s1 and the i-th character of s2.
For example, f("ab", "ba") = "aa", and f("nzwzl", "zizez") = "niwel".
You found two strings x and y of the same length and consisting of only lowercase English letters. Find any string z such that f(x, z) = y, or print -1 if no such string z exists.
Input
The first line of input contains the string x.
The second line of input contains the string y.
Both x and y consist only of lowercase English letters, x and y have same length and this length is between 1 and 100.
Output
If there is no string z such that f(x, z) = y, print -1.
Otherwise, print a string z such that f(x, z) = y. If there are multiple possible answers, print any of them. The string z should be the same length as x and y and consist only of lowercase English letters.
Examples
input
ab
aa
output
ba
input
nzwzl
niwel
output
xiyez
input
ab
ba
output
-1

solution:
Greedy.
If any of the characters in y is greater than which in x, put "-1".
Or just print y.
code:
#include <bits/stdc++.h>
using namespace std;
string x, y;
char z[105];
int main(){
 cin >> x >> y;
 int l = x.size();
 for(int i = 0; i < l; i++){
  if(y[i] <= x[i]){
   z[i] = y[i];
  }
  else {
   cout << "-1\n";
   return 0;
  }
 }
 for(int i = 0; i < l; i++){
  cout << z[i];
 }
 cout << endl;
 return 0;
}

C. Voltage Keepsake
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You have n devices that you want to use simultaneously.
The i-th device uses ai units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·ai units of power. The i-th device currently has bi units of power stored. All devices can store an arbitrary amount of power.
You have a single charger that can plug to any single device. The charger will add p units of power per second to a device. This charging is continuous. That is, if you plug in a device for λ seconds, it will gain λ·p units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible.
You are wondering, what is the maximum amount of time you can use the devices until one of them hits 0 units of power.
If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.
Input
The first line contains two integers, n and p (1 ≤ n ≤ 100 0001 ≤ p ≤ 109) — the number of devices and the power of the charger.
This is followed by n lines which contain two integers each. Line i contains the integers ai and bi (1 ≤ ai, bi ≤ 100 000) — the power of the device and the amount of power stored in the device in the beginning.
Output
If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.
Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4.
Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
Examples
input
2 1
2 2
2 1000
output
2.0000000000
input
1 100
1 1
output
-1
input
3 5
4 3
5 2
6 1
output
0.5000000000

solution:
Greedy.
1. Find the time takes to die for each device: t(i).
2. sort the time in an increasing order.
3. if we use power on first x devices, the time T(x) it takes them to die out is (sum of initial powers of first x devices) / (sum of the rate of decreasing of the first x devices - p). 
4. if T(x) < t(x + 1) then break and print T(x), or continue to add device. (x++).
Code:
#include <bits/stdc++.h>
using namespace std;
const int INF = ~0U>>1;
int n, p;
double rate, total;
struct NODE{
 int dec, ini;
 double time;
}t[100005];
bool cmp(NODE o, NODE w){
 return o.time < w.time;
}
int main(){
 scanf("%d%d", &n, &p);
 bool flag = 0;
 for(int i = 1; i <= n; i++){
  scanf("%d%d", &t[i].dec, &t[i].ini);
  t[i].time = 1.0 * t[i].ini / t[i].dec;
  rate += t[i].dec;
 }
 if(p >= rate){
  return (printf("-1\n")), 0;
 }
 double krate = 0;
 sort(t + 1, t + n + 1, cmp);
 t[n + 1].time = INF;
 for(int i = 1; i <= n; i++){
  total += t[i].ini;
  krate += t[i].dec;
  if(krate - p <= 0) continue;
  if(1.0 * total / (krate - p) <= t[i + 1].time){
   printf("%.12lf\n", 1.0 * total / (krate - p));
   return 0;
  }
 }
 printf("%.12lf\n", 1.0 * total / (krate - p));
return 0;
}

D. Volatile Kite
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.
You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.
Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.
Input
The first line has one integer n (4 ≤ n ≤ 1 000) — the number of vertices.
The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).
Output
Print one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex.
Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
Examples
input
4
0 0
0 1
1 1
1 0
output
0.3535533906
input
6
5 0
10 0
12 -4
10 -8
5 -8
3 -4
output
1.0000000000

Solution:
1. The maximum available vibration=1/2* the distance from node i to the line formed by nodes i - 1 and i + 1.
formula for the distance : 
then use some math to solve.
Code:
#include <bits/stdc++.h>
using namespace std;
const int INF = ~0U>>1;
int n;
double x[1003], y[1003], ans;
int main(){
 scanf("%d", &n);
 for(int i = 1; i <= n; i++){
  scanf("%lf%lf", &x[i], &y[i]);
 }
 x[n + 1] = x[1];
 y[n + 1] = y[1];
 x[0] = x[n];
 y[0] = y[n];
 ans = INF;
 for(int i = 1; i <= n; i++){
  if(x[i + 1] == x[i - 1]){
   if(abs((x[i] - x[i - 1]) / 2) < ans) ans = abs((x[i] - x[i - 1]) / 2);
   continue;
  }
  double slope = 1.0 * (1.0 * y[i + 1] - y[i - 1]) / (x[i + 1] - x[i - 1]);
  double inter = 1.0 * y[i + 1] - slope * x[i + 1];
  double a = slope, c = inter;
  double dis;
  dis = abs((a * x[i] - 1.0 * y[i] + c) / sqrt(1.0 * (1.0 * a * a + 1.0)) / 2);
  if(dis < ans) ans = dis;
 }
 printf("%.12lf\n", ans);
return 0;
}

 


Tuesday, February 21, 2017

Topcoder SRM 709 DIV 2 500pt Permatchd2 solution

Problem Statement

    Hero has a simple undirected graph. (Simple means that each edge connects two different vertices, and each pair of vertices is connected by at most one edge.)
A graph is considered pretty if it is a simple undirected graph in which each connected component contains an even number of edges.
You are given the adjacency matrix of Hero's graph as a vector <string> graph. ('Y' means that the two vertices are connected by an edge, 'N' means that they aren't.)
Change Hero's graph into a pretty graph by adding as few edges as possible. Return the minimum number of edges you have to add, or -1 if Hero's graph cannot be changed into a pretty graph.

Definition

    
Class:Permatchd2
Method:fix
Parameters:vector <string>
Returns:int
Method signature:int fix(vector <string> graph)
(be sure your method is public)

Limits

    
Time limit (s):2.000
Memory limit (MB):256
Stack limit (MB):256

Notes

-Don't forget that the graph you'll obtain after adding the edges must still be simple.

Constraints

-n will be between 1 and 50, inclusive.
-graph will contain exactly n elements.
-Each element in graph will contain exactly n characters.
-Each character in graph will be either 'N' or 'Y'.
-For all valid i graph[i][i] will be equal to 'N'.
-For all valid i, j graph[i][j] will be equal to graph[j][i].

Examples

0)
    
{"NYN",
 "YNN",
 "NNN"}
Returns: 1
This is the adjacency matrix of a simple graph on three vertices. Two of the three vertices are connected by an edge. Here, an optimal solution is to add one edge that will connect the remaining vertex to one of the other two. The resulting graph is a simple graph with a single connected component. The connected component contains two edges, which is an even number.
1)
    
{"NYY",
 "YNN",
 "YNN"}
Returns: 0
2)
    
{"NYY",
 "YNY",
 "YYN"}
Returns: -1
3)
    
{"NYYY",
 "YNYY",
 "YYNN",
 "YYNN"}
Returns: 1
4)
    
{"NYNNNN",
 "YNNNNN",
 "NNNYNN",
 "NNYNNN",
 "NNNNNY",
 "NNNNYN"}
Returns: 3
5)
    
{"N"}
Returns: 0
This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.

Solution:

  The size of the number of nodes is less than 50, which means we can use direct search on graph.
  First, we build the graph.
  Second, search all the nodes that have not been searched. Create unions with edge and nodes numbers.
  Then we search all the unions and record the number of ugly unions(unions that have odd number of edges).
   If there's only one ugly union in the whole graph, we want to see if all the nodes are connected. If not, we could connect any pair of unconnected nodes to make it a pretty graph. print "1".
   If there exists at least one union with even number of edges, we could create a pretty graph by connecting all ugly unions to this pretty union. print the number of ugly unions.
   If there's only ugly unions in the graph, we connect all of them together and add one edge to any pair of unconnected nodes to make it a pretty graph. print the number of ugly unions - 1 + 1 = number of ugly unions.
  The interesting magic of this problem is that we can reduce the cases to two: only one ugly union & exists at least one pretty union.


Codes:

// BEGIN CUT HERE

// END CUT HERE
#line 5 "Permatchd2.cpp"
#include<bits/stdc++.h>
using namespace std;
int a[55][55];
int size[55];
int edge, node;
int vis[55];
int kk[55], gg[55];
int ss;
bool flag;
void dfs(int root){
vis[root] = 1;
edge += size[root];
for(int i = 1; i <= size[root]; i++){
if(!vis[a[root][i]]){
node++;
dfs(a[root][i]);
}
}
}
class Permatchd2 {
public:
int fix(vector <string> graph) {
int n = graph.size();
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(graph[i][j] == 'Y') size[i]++, a[i][size[i]] = j;
}
}
for(int i = 0; i < n; i++){
edge = 0, node = 1;
if(!vis[i]){
ss++;
dfs(i);
kk[ss] = edge / 2;
gg[ss] = node;
if(kk[ss] < node * (node - 1) / 2){
flag = 1;
}
}
}
int count = 0;
for(int i = 1; i <= ss; i++){
if(kk[i] % 2 == 1) count++;
}
//return count;
int ans = 0, remain = ss - count;
if(ss == 1 && count == 1) {
if(flag) return 1;
else return (-1);
}
else return count;
}
};

Topcoder SRM 709 DIV 2 250pt Robofactory solution

Problem Statement

    Hero owns a factory. There are n robots working at the factory. The robots are numbered 0 through n-1.
Today, exactly one of the robots became corrupted. Hero has decided to give all robots a test that may determine the number of the corrupted robot. The test works as follows: For each x from 0 to n-1, in order, Hero tells robot x a positive integer and the robot answers whether the integer is odd or even. Each normal robot will always give the correct answer. The corrupted robot may sometimes give the opposite answer. More precisely: the corrupted robot will answer incorrectly if and only if the previous robot was given an odd number. In particular, if robot 0 is the corrupted robot, it will give the correct answer (as there is no previous robot).
You are given a log of the test: a vector <int> query and a vector <string> answer, each with n elements. For each x, query[x] is the positive integer given to robot x, and answer[x] is the answer given by the robot: either "Odd" or "Even".
It is guaranteed that the situation described by query and answer could have occurred as described above. If it is possible to determine the index of the corrupted robot, return it. Otherwise, return -1.

Definition

    
Class:Robofactory
Method:reveal
Parameters:vector <int>, vector <string>
Returns:int
Method signature:int reveal(vector <int> query, vector <string> answer)
(be sure your method is public)

Limits

    
Time limit (s):2.000
Memory limit (MB):256
Stack limit (MB):256

Constraints

-n will be between 1 and 50, inclusive.
-query and answer will contain exactly n elements.
-Each element in query will be between 1 and 1000, inclusive.
-Each element in answer will be either "Odd" or "Even".
-It is guaranteed that there will be at least one possible number of the corrupted robot.

Examples

0)
    
{3,2,2}
{"Odd", "Odd", "Even"}
Returns: 1
Robot 1 gave the wrong answer. Thus, robot 1 is the corrupted robot.
1)
    
{1,3,5,10}
{"Odd", "Odd", "Odd", "Even"}
Returns: 0
All robots gave correct answers. Still, we can deduce that the corrupted robot must be robot 0. For example, robot 1 cannot be the corrupted robot: as robot 0's number was odd, robot 1 would have answered incorrectly if it were corrupted.
2)
    
{2,3,5,10}
{"Even", "Odd", "Odd", "Even"}
Returns: -1
Again, all robots gave correct answers. This time we cannot be sure which robot is corrupted. All we know is that it is either robot 0 or robot 1. Both possibilities are consistent with the given input data. Thus, we should return -1.
3)
    
{2,4,6,10}
{"Even", "Even", "Even", "Even"}
Returns: -1
4)
    
{107}
{"Odd"}
Returns: 0
5)
    
{1,1,1}
{"Odd", "Odd", "Even"}
Returns: 2
This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.


Solution:

  The key of this problem is to remember that there's exactly one corrupted robot. We could assume that robot#0 is not at first, and then search the next n - 1 robots. Once we find a robot that does not satisfy "the corrupted robot will answer incorrectly if and only if the previous robot was given an odd number", it's the corrupted robot. When we are searching throw robot #1 to robot #n - 1, we record the number of robots whose previous robot number is even because we cannot judge if the robot is the corrupted one.
  Finally, if we have more than 0 robots undecided with 0 robots that are corrupted, print "-1" because we don't know which one is corrupted between robot #0 and robots undecided.
if we have 0 robots undecided remained, print "0" because we know there's one robot that is corrupted and it must be robot #0.

Code:

#include <bits/stdc++.h>
using namespace std;
int a[1002];
map <string, int> m;
class Robofactory{
  public:
    int reveal(vector<int> query, vector <string> answer){
    m["Odd"] = 1, m["Even"] = 0;
    int different = 0, wrong = -1;
    a[0] = query[0] % 2;
        //if(a[0] == m[answer[0]]) wrong++; else different++;
    for(int i = 1; i < query.size(); i++){
    a[i] = query[i] % 2;
    if(a[i - 1] == 0) different++;
    if(m[answer[i]] != a[i]){
    if(a[i - 1] == 1) wrong = i;
    }
    }
    if(wrong != -1) {
    return wrong;
    }
    else{
     if(different == 0) return 0;
     else return (-1);
    }
    }
};

Monday, August 29, 2016

Codeforces Round #369 (Div. 2)

A. Bus to Udayland
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has nrows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.
ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of rows of seats in the bus.
Then, n lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row.
Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details.
Output
If it is possible for Chris and ZS to sit at neighbouring empty seats, print "YES" (without quotes) in the first line. In the next n lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output).
If there is no pair of seats for Chris and ZS, print "NO" (without quotes) in a single line.
If there are multiple solutions, you may print any of them.
Examples
input
6
OO|OX
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX
output
YES
++|OX
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX
input
4
XO|OX
XO|XX
OX|OX
XX|OX
output
NO
input
5
XX|XX
XX|XX
XO|OX
XO|OO
OX|XO
output
YES
XX|XX
XX|XX
XO|OX
XO|++
OX|XO
Note
Note that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.
O+|+X
XO|XX
OX|OO
XX|OX
OO|OO
OO|XX
By Gerry99, contest: Codeforces Round #369 (Div. 2), problem: (A) Bus to Udayland, Accepted#

#include <bits/stdc++.h>
const int INF = ~0U >> 1;
using namespace std;
char ch[1002][6], x, y;
int main(){
 int n;
 cin >> n;
 for(int i = 1; i <= n; i++){
  for(int j = 1; j <= 5; j++){
   cin >> ch[i][j];
  }
 }
 bool flag = 0;
 for(int i = 1; i <= n; i++){
  if(ch[i][1] == 'O' && ch[i][2] == 'O') {
   ch[i][1] = ch[i][2] = '+';
   flag = 1;
   break;
  }
  else if(ch[i][4] == 'O' && ch[i][5] == 'O') {
   ch[i][4] = ch[i][5] = '+';
   flag = 1;
   break;
  }
 }
 if(!flag) printf("NO\n");
 else {
  printf("YES\n");
  for(int i = 1; i <= n; i++){
   for(int j = 1; j <= 5; j++) cout << ch[i][j];
   cout << endl;
  }
 }
 return 0;
}





B. Chris and Magic Square
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.
Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal —  and the secondary diagonal — ) are equal.
Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible?
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid.
n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive.
It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0.
Output
Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output  - 1 instead.
If there are multiple solutions, you may print any of them.
Examples
input
3
4 0 2
3 5 7
8 1 6
output
9
input
4
1 1 1 1
1 1 0 1
1 1 1 1
1 1 1 1
output
1
input
4
1 1 1 1
1 1 0 1
1 1 2 1
1 1 1 1
output
-1
Note
In the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed,
The sum of numbers in each row is:
4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.
The sum of numbers in each column is:
4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.
The sum of numbers in the two diagonals is:
4 + 5 + 6 = 2 + 5 + 8 = 15.
In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square.

By Gerry99, contest: Codeforces Round #369 (Div. 2), problem: (B) Chris and Magic Square, Accepted#

#include <bits/stdc++.h>
const int INF = ~0U >> 1;
using namespace std;
int n;
long long a[502][502], needx, needy, x[502], y[502], valx, valy, hhx, hhy, dig1, dig2;
int main(){
 scanf("%d", &n);
 for(int i = 1; i <= n; i++){
  for(int j = 1; j <= n; j++){
   scanf("%lld", &a[i][j]);
   if(a[i][j] == 0) needx = i, needy = j;
  }
 }
 if(n == 1) return (printf("1\n")), 0;
 for(int i = 1; i <= n; i++){
  if(i != needx){
   for(int j = 1; j <= n; j++){
    x[i] += a[i][j];
   }
   if(valx == 0) valx = x[i];
   else if(valx != x[i]) return (printf("-1\n")), 0;
  }
 }
 for(int j = 1; j <= n; j++){
  if(j != needy){
   for(int i = 1; i <= n; i++){
    y[j] += a[i][j];
   }
   if(valx == 0) valx = y[j];
   else if(valx != y[j]) return (printf("-1\n")), 0;
  }
 }
 for(int i = 1; i <= n; i++){
  hhx += a[needx][i], hhy += a[i][needy];
 }
 if(hhx != hhy) return (printf("-1\n")), 0;
 else a[needx][needy] = valx - hhx;
 for(int i = 1; i <= n; i++)dig1 += a[i][i], dig2 += a[i][n - i + 1];
 if(dig1 != dig2 || a[needx][needy] <= 0 || dig1 != valx || dig2 != valx) printf("-1\n");
 else printf("%lld\n", a[needx][needy]);
 return 0;
}
C. Coloring Trees
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.
Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≤ ci ≤ m, where ci = 0 means that tree i is uncolored.
ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ci = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi, j litres of paint.
The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}.
ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.
Please note that the friends can't color the trees that are already colored.
Input
The first line contains three integers, nm and k (1 ≤ k ≤ n ≤ 1001 ≤ m ≤ 100) — the number of trees, number of colors and beauty of the resulting coloring respectively.
The second line contains n integers c1, c2, ..., cn (0 ≤ ci ≤ m), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci.
Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi, j (1 ≤ pi, j ≤ 109) — the amount of litres the friends need to color i-th tree with color jpi, j's are specified even for the initially colored trees, but such trees still can't be colored.
Output
Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print  - 1.
Examples
input
3 2 2
0 0 0
1 2
3 4
5 6
output
10
input
3 2 2
2 1 2
1 3
2 4
3 5
output
-1
input
3 2 2
2 0 0
1 3
2 4
3 5
output
5
input
3 2 3
2 1 2
1 3
2 4
3 5
output
0
Note
In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color).
In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is - 1.
In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0.
By Gerry99, contest: Codeforces Round #369 (Div. 2), problem: (C) Coloring Trees, Accepted#


#include <bits/stdc++.h>
const int INF = ~0U >> 1;
using namespace std;
int n, m, k;
long long w[102][102], dp[102][102][102], color[102];
int main(){ 
 scanf("%d%d%d", &n, &m, &k);
 for(int i = 1; i <= n; i++) scanf("%lld", &color[i]);
 for(int i = 1; i <= n; i++){
  for(int j = 1; j <= m; j++) scanf("%lld", &w[i][j]);
 }
 for(int i = 0; i <= n; i++){
  for(int j = 0; j <= k; j++){
   for(int l = 0; l <= m; l++) dp[i][j][l] = 1000000000000;
  }
 }
 if(color[1] > 0) dp[1][1][color[1]] = 0;
 else for(int i = 1; i <= m; i++) dp[1][1][i] = w[1][i];
 for(int i = 1; i <= n; i++){
  for(int j = 1; j <= min(k, i); j++){
   if(color[i] == 0){
    if(color[i - 1] == 0){
     for(int l = 1; l <= m; l++)
      for(int p = 1; p <= m; p++){
       if(l == p) dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j][l] + w[i][l]);
       else dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j - 1][p] + w[i][l]);
      }
    }
    else{
     for(int l = 1; l <= m; l++)
      if(l == color[i - 1]) dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j][l] + w[i][l]);
      else dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j - 1][color[i - 1]] + w[i][l]);
    }
   }
   else {
    if(color[i - 1] == 0){
     for(int l = 1; l <= m; l++) 
      if(l == color[i]) dp[i][j][color[i]] = min(dp[i][j][color[i]], dp[i - 1][j][color[i]]);
      else dp[i][j][color[i]] = min(dp[i][j][color[i]], dp[i - 1][j - 1][l]);
    }
    else{
     if(color[i] == color[i - 1]) dp[i][j][color[i]] = min(dp[i][j][color[i]], dp[i - 1][j][color[i]]);
     else dp[i][j][color[i]] = dp[i - 1][j - 1][color[i - 1]];
    }
   }
  }
 }
 long long ans = 1000000000000;
 if(color[n] == 0){
  for(int i = 1; i <= m; i++) {
   ans = min(ans, dp[n][k][i]);
  }
 }
 else ans = dp[n][k][color[n]];
 if(ans == 1000000000000) printf("-1\n");
 else printf("%lld\n", ans);
 return 0;
}