HackerRank |道路与图书馆|在某些测试案例中得到错误答案

时间:2019-08-22 07:30:36

标签: c#

我的方法:

根据该问题,我们必须将修复库和道路的成本降至最低。所以我所做的是if the cost of repairing the lib is <= cost of repairing the roads,然后我只是return (numberOfCities * costOfRepairingLib)。否则,我计算连接零件的数量和要维修的道路的数量,然后计算成本并退还。

我无法通过4、5、6、8、9和10个测试用例,并且这些测试用例是如此之大,以至于我什至无法调试。请查看我在哪里弄错了。

Link to the problem


我觉得逻辑很好,但是即使我将每种数据类型都更改为long,它也无法在大型测试用例中使用。我真的很坚持。

class Solution {

    // Complete the roadsAndLibraries function below.
    static long roadsAndLibraries(long n, long c_lib, long c_road, long[][] cities) {
        if(c_lib <= c_road || c_road == 0)
            return c_lib * n;

        long[,] adjacentMatrix = new long[n, n];
        Stack<long> stack = new Stack<long>();
        Dictionary<long, bool> notVisited = new Dictionary<long, bool>();
        Dictionary<long, bool> visited = new Dictionary<long, bool>();

        for(long i = 1; i <= n; i++){
            notVisited[i] = false;
        }

        foreach(var city in cities){
            adjacentMatrix[city[0] - 1,city[1] -1] = 1;
            adjacentMatrix[city[1] - 1,city[0] - 1] = 1;
        }

        long noOfCycles = 0;
        long noOfRoads = 0;

        while(notVisited.Count > 0){
            stack.Push(notVisited.ElementAt(0).Key);
            visited.Add(stack.Peek(), true);
            notVisited.Remove(notVisited.ElementAt(0).Key);
            noOfCycles++;
            while(stack.Count > 0){
                long top = stack.Pop();
                for(long i = 0; i < n; i++){
                    if(adjacentMatrix[top - 1, i] == 1 && !visited.ContainsKey(i + 1)){
                        visited.Add(i + 1, true);
                        noOfRoads++;
                        stack.Push(i + 1);
                        notVisited.Remove(i + 1);
                    }
                }
            }
        }

        return (noOfCycles * c_lib) + (noOfRoads * c_road);
    }

    static void Main(string[] args) {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        long q = Convert.ToInt64(Console.ReadLine());

        for (long qItr = 0; qItr < q; qItr++) {
            string[] nmC_libC_road = Console.ReadLine().Split(' ');

            long n = Convert.ToInt64(nmC_libC_road[0]);

            long m = Convert.ToInt64(nmC_libC_road[1]);

            long c_lib = Convert.ToInt64(nmC_libC_road[2]);

            long c_road = Convert.ToInt64(nmC_libC_road[3]);

            long[][] cities = new long[m][];

            for (long i = 0; i < m; i++) {
                cities[i] = Array.ConvertAll(Console.ReadLine().Split(' '), citiesTemp => Convert.ToInt64(citiesTemp));
            }

            long result = roadsAndLibraries(n, c_lib, c_road, cities);

            textWriter.WriteLine(result);
        }

        textWriter.Flush();
        textWriter.Close();
    }
}

2 个答案:

答案 0 :(得分:0)

所以我发现了我的代码出了什么问题

我的逻辑是完全正确的,因为我无法猜测发生了什么事情,因为 HACKERRANK 处理了 OutOfMemoryException 错误,它们显示错误的答案而不是显示例外。因此,我更改了代码以提高时间和空间的复杂性。

所以我做的是:

  1. 我删除了两个 dictionary (已访问和notVisited),并添加了一个访问过的 array ,因为数组查找会更快,因为字典查找是两个操作:计算键的哈希值以获得索引,并从该索引处的内部数组中检索值。

  2. 使用了邻接表而不是邻接矩阵

代码:

class Solution {

    // Complete the roadsAndLibraries function below.
    static long roadsAndLibraries(long n, long c_lib, long c_road, long[][] cities) {
        if(c_lib <= c_road || cities.Length == 0)
            return c_lib * n;

        long[,] adjacentMatrix = new long[n + 1, n + 1];
        Stack<long> stack = new Stack<long>();
        bool[] visited = new bool[n + 1];

        foreach(var city in cities){
            adjacentMatrix[city[0], city[1]] = 1;
            adjacentMatrix[city[1], city[0]] = 1;
        }

        // for(int i = 0; i < n + 1; i++){
        //     for(int j = 0; j < n + 1; j++){
        //         Console.Write(adjacentMatrix[i,j]+" ");
        //     }
        //     Console.WriteLine();
        // }

        long noOfComponents = 0;
        long noOfEdges = 0;

        for(long i = 1; i <= n; i++){
            if(visited[i]){
                continue;
            }
            stack.Push(i);
            visited[i] = true;
            noOfComponents++;
            while(stack.Count > 0){
                long top = stack.Pop();
                for(long j = 0; j <= n; j++){
                    if(!visited[j] && adjacentMatrix[top,j] == 1){
                        stack.Push(j);
                        visited[j] = true;
                        noOfEdges++;
                    }
                }
            }
        }

        // Console.WriteLine(noOfCycles+" "+noOfRoads);

        return noOfComponents * c_lib + noOfEdges * c_road;
    }

    static void Main(string[] args) {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        long q = Convert.ToInt64(Console.ReadLine());

        for (long qItr = 0; qItr < q; qItr++) {
            string[] nmC_libC_road = Console.ReadLine().Split(' ');

            long n = Convert.ToInt64(nmC_libC_road[0]);

            long m = Convert.ToInt64(nmC_libC_road[1]);

            long c_lib = Convert.ToInt64(nmC_libC_road[2]);

            long c_road = Convert.ToInt64(nmC_libC_road[3]);

            long[][] cities = new long[m][];

            for (long i = 0; i < m; i++) {
                cities[i] = Array.ConvertAll(Console.ReadLine().Split(' '), citiesTemp => Convert.ToInt64(citiesTemp));
            }

            long result = roadsAndLibraries(n, c_lib, c_road, cities);

            textWriter.WriteLine(result);
        }

        textWriter.Flush();
        textWriter.Close();
    }
}

答案 1 :(得分:0)

我编写了以下代码来解决问题,但 13 次测试中仍有 6 次失败。如何通过所有测试?

   using System.CodeDom.Compiler;
   using System.Collections.Generic;
   using System.Collections;
   using System.ComponentModel;
   using System.Diagnostics.CodeAnalysis;
   using System.Globalization;
   using System.IO;
   using System.Linq;
   using System.Reflection;
   using System.Runtime.Serialization;
   using System.Text.RegularExpressions;
   using System.Text;
   using System;

 class Result
 {

/*
 * Complete the 'roadsAndLibraries' function below.
 *
 * The function is expected to return a LONG_INTEGER.
 * The function accepts following parameters:
 *  1. INTEGER n
 *  2. INTEGER c_lib
 *  3. INTEGER c_road
 *  4. 2D_INTEGER_ARRAY cities
 */
static Dictionary<int, List<int>> adj;
static long costRd;
static bool[] visited;
private static long nconnected;
public static long roadsAndLibraries(int n, int c_lib, int c_road, List<List<int>> cities)
{
    if(c_lib <= c_road ) return n*c_lib;
    costRd = 0;
    nconnected = 0;
    visited= new bool[n +1];

    adj = new Dictionary<int, List<int>>();  
    for (int i =0; i< cities.Count(); i++) {
        int u = cities[i][0];
        int v = cities[i][1];
        if (!adj.ContainsKey(u)) {
            var list = new List<int> ();
            adj[u] = list;
        }         
        adj[u].Add(v);
        if (!adj.ContainsKey(v)) {
            var list = new List<int> ();
            adj[v] = list;
        }
        adj[v].Add(u);                
    } 
    for(int i =0; i< n; i++) {
        if(!visited[i+1]) {   
          nconnected++;
          DFS( i+ 1);            
        }
    }
    return costRd *c_road + nconnected * c_lib;
}
private static void DFS(int node)
{
  visited[node] =true;
  if (!adj.ContainsKey(node)) return;
  foreach( var num in adj[node]) {
    if(!visited[num]){
      costRd++;
      DFS(num);            
    }
  }   
  }
 }

 class Solution
 {
   public static void Main(string[] args)
  {
     TextWriter textWriter = new 
     StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

     int q = Convert.ToInt32(Console.ReadLine().Trim());

    for (int qItr = 0; qItr < q; qItr++)
    {
        string[] firstMultipleInput = Console.ReadLine().TrimEnd().Split(' ');

        int n = Convert.ToInt32(firstMultipleInput[0]);

        int m = Convert.ToInt32(firstMultipleInput[1]);

        int c_lib = Convert.ToInt32(firstMultipleInput[2]);

        int c_road = Convert.ToInt32(firstMultipleInput[3]);

        List<List<int>> cities = new List<List<int>>();

        for (int i = 0; i < m; i++)
        {
            cities.Add(Console.ReadLine().TrimEnd().Split(' ').ToList().Select(citiesTemp => Convert.ToInt32(citiesTemp)).ToList());
        }

        long result = Result.roadsAndLibraries(n, c_lib, c_road, cities);

        textWriter.WriteLine(result);
    }

    textWriter.Flush();
    textWriter.Close();
  }
 }