fork download
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4.  
  5. public static void main(String[] args) {
  6. Scanner scanner = new Scanner(System.in);
  7. int n = scanner.nextInt();
  8. int[][] connectivityMatrix = new int[n][n];
  9. int[] maintenanceCosts = new int[n];
  10. scanner.nextLine();
  11. for (int i = 0; i < n; i++) {
  12. String line = scanner.nextLine();
  13. for (int j = 0; j < n; j++) {
  14. connectivityMatrix[i][j] = line.charAt(j) - '0';
  15. }
  16. }
  17. for (int i = 0; i < n; i++) {
  18. maintenanceCosts[i] = scanner.nextInt();
  19. }
  20. scanner.close();
  21. long totalCost = 0;
  22. for (int i = 0; i < n; i++) {
  23. if (isSuperTunnel(connectivityMatrix, i)) {
  24. totalCost += maintenanceCosts[i];
  25. }
  26. }
  27. System.out.println(totalCost);
  28. }
  29.  
  30. private static boolean isSuperTunnel(int[][] connectivityMatrix, int tunnel) {
  31. int n = connectivityMatrix.length;
  32. for (int i = 0; i < n; i++) {
  33. if (i != tunnel && connectivityMatrix[tunnel][i] == 1) {
  34. for (int j = 0; j < n; j++) {
  35. if (j != tunnel && j != i && connectivityMatrix[tunnel][j] == 1 && connectivityMatrix[i][j] == 0) {
  36. return false;
  37. }
  38. }
  39. }
  40. }
  41. return true;
  42. }
  43. }
Success #stdin #stdout 0.16s 54624KB
stdin
8
0 1 1 0 0 0 0 0
1 0 0 1 0 0 0 0
1 0 0 1 0 0 1 1
0 1 1 0 1 1 0 0
0 0 0 1 0 1 0 0
0 0 0 1 1 0 0 0
0 0 1 0 0 0 0 1
0 0 1 0 0 0 1 0
2 3 5 1 6 4 2 7
stdout
19