c - 获取子矩阵中不同元素的数量

标签 c arrays algorithm distinct-values

这是 a problem from the December 2013 CodeChef Challenge比赛已经结束。

问题陈述:

Input: Square matrix of order n and a query which will denote the submatrix.

(x1, y1, x2, y2)

x1, y1 denotes the upper left and x2, y2 denotes the lower right end of submatrix.

Output: Number of distinct elements in this submatrix.

Constraints:

  • Time limit = 1 sec
  • 1 ≤ N ≤ 300
  • 1 ≤ Q ≤ 10^5
  • 1 ≤ Ai,j ≤ 10
  • 1 ≤ X1 ≤ X2 ≤ N
  • 1 ≤ Y1 ≤ Y2 ≤ N

这是我试过的:

#include<stdio.h>
//#include<conio.h>
int main()
{
  //clrscr();
  int a[300][300], test[100000], count[10], m, n, c, j, p, q, r, s;
  long qu, re, i;

  scanf("%d", &n);

  for (i = 0; i < n; i++)
  {
    for (j = 0; j < n; j++)
    {
      scanf("%d", &a[i][j]);
    }
  }

  scanf("%ld", &qu);
  for (re = 0; re < qu; re++)
  {
    c = 0;
    for(i = 0; i < 10; i++)
    {
      count[i] = 0;
    }

    scanf("%d %d %d %d", &p, &q, &r, &s);
    for (i = (p-1); i < r; i++)
    {
      for (j = (q-1); j < s; j++)
      {
        m = a[i][j];
        count[--m]++;
      }
    }

    for (i = 0; i < 10; i++)
    {
      if (count[i] != 0)
      {
        c++;
      }
    }
    test[re] = c;
  }

  for(i = 0; i < qu; i++)
  {
    printf("%d\n", test[i]);
  }

  //getch();
  return 0;
}

但是我遇到了一个 TLE(超出时间限制)错误。

它必须对每个数字的累积频率做一些事情。

有人可以针对这个问题提出一个有效的算法吗?

最佳答案

初始化并跟踪 HashMap 。

遍历子矩阵的条目,对于每个条目,

  • 检查它是否已经在 HashMap 中;
  • 如果不是,则将 total_distinct_entries 加 1,并将此条目添加到 HashMap 中。

参见 http://en.wikipedia.org/wiki/Hash_table .

编辑:另见 http://en.wikipedia.org/wiki/Set_data_structure ,特别是关于实现的部分。在 C++ 中,标准库中提供了一个 std::set 数据结构。

关于c - 获取子矩阵中不同元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20727021/

相关文章:

c - 带字符串数组的 strcpy

java - 哈希表替代方案以获得更好的性能

c - 为什么 fscanf 不转换 set 然后转换 char?

c - 将字符串传递给函数从中获取整数数组

arrays - 如何将固定长度的十六进制 rune 数组转换为单个整数

algorithm - 分而治之,动态规划和贪心算法!

java - 使用快速选择算法在未排序的数组中查找中位数

javascript - 菱形方 block 算法不起作用(将代码从 JS 重写为 JAVA)

c - 如果用户选择特定功能,则结束循环

c - 在C中的排序数组中插入一个元素的函数