首页 \ 问答 \ 包含该点的三角形数量(0,0)(Number of Triangles Containing The Point (0,0))

包含该点的三角形数量(0,0)(Number of Triangles Containing The Point (0,0))

首先,对Topcoder的信用,因为这个问题在他们的一个SRM中使用(但他们没有编辑...)

在这个问题中,我给了n个点(其中n在1到1000之间)。 对于每三个点,显然有一个连接它们的三角形。 问题是,这些三角形中有多少包含点(0,0)。

我试过在堆栈上查看这个线程:

一个点周围的三角形点

但我无法理解使用什么数据结构/如何使用它们来解决这个问题。

这个问题的一个明显天真的解决方案是使用低效的O(n ^ 3)算法并搜索所有点。 但是,有人可以帮助我提高效率,并在O(n ^ 2)时间内完成此操作吗?

以下是Petr对这个问题的解决方案......它很短,但有一个我无法理解的大创意。

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class TrianglesContainOrigin {
    public long count(int[] x, int[] y) {
        int n = x.length;
        long res = (long) n * (n - 1) * (n - 2) / 6;
        for (int i = 0; i < n; ++i) {
            int x0 = x[i];
            int y0 = y[i];
            long cnt = 0;
            for (int j = 0; j < n; ++j) {
                int x1 = x[j];
                int y1 = y[j];
                if (x0 * y1 - y0 * x1 < 0) {
                    ++cnt;
                }
            }
            res -= cnt * (cnt - 1) / 2;
        }
        return res;
    }
}

First off, credits to Topcoder, as this problem was used in one of their SRMs (but they have no editorial for it..)

In this problem, I am given n points (where n is between 1 and 1000). For every three points, there is obviously a triangle that connects them. The question is, how many of these triangles contain the point (0,0).

I have tried looking at this thread on stack:

triangle points around a point

But I am unable to understand what data structures are used/how to use them to solve this problem.

An obvious naive solution to this problem is to use an inefficient O(n^3) algorithm and search all points. However, could someone please help me make this more efficient, and do this in O(n^2) time?

Below is Petr's solution to this problem... it is very short, but has a large idea I cannot understand.

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class TrianglesContainOrigin {
    public long count(int[] x, int[] y) {
        int n = x.length;
        long res = (long) n * (n - 1) * (n - 2) / 6;
        for (int i = 0; i < n; ++i) {
            int x0 = x[i];
            int y0 = y[i];
            long cnt = 0;
            for (int j = 0; j < n; ++j) {
                int x1 = x[j];
                int y1 = y[j];
                if (x0 * y1 - y0 * x1 < 0) {
                    ++cnt;
                }
            }
            res -= cnt * (cnt - 1) / 2;
        }
        return res;
    }
}

原文:https://stackoverflow.com/questions/27713046
更新时间:2022-03-28 12:03

最满意答案

因此,对于问题的这一部分,有一个绝对的答案:

为什么malloc失败,但不返回NULL。 这可能是可能的,或者我得到的错误信息的原因是其他吗?

在Linux中,默认情况下,用于分配内存的内核接口几乎不会彻底失败。 相反,他们以这样的方式设置页表 :首次访问所请求的内存时,CPU将产生页面错误 ,此时内核会处理此错误 ,并查找将用于此目的的物理内存(虚拟)页面。 所以,在内存不足的情况下,你可以向内核请求内存,它会“成功”,并且当你第一次尝试触摸它返回的内存时, 是分配实际上失败的时候,导致进程失效。 (或者也许还有其他一些不幸的受害者,这里有一些启发式的,我不是很熟悉,请参阅“ oom-killer ”。)

你的其他一些问题,答案对我来说不太清楚。

为什么在gdb下运行时以及没有调试器时,这种行为会有所不同?
这可能(只是一个猜测)GDB有自己的 malloc ,并且正在跟踪你的分配。 在一个相关的问题上,我经常发现我的代码中的堆错误在调试器中通常是不可重现的。 这是令人沮丧的,并让我挠了脑袋,但它基本上是我想到的一个人必须忍受的事情......

我该如何解决?

这是一个大锤解决方案(也就是说,它改变了所有进程的行为,而不仅仅是你自己的行为,而且你的程序改变全局状态通常不是一个好主意),但是你可以编写字符串2/proc/sys/vm/overcommit_memory 。 查看我从Google搜索中获得的这个链接

如果没有......我只是确保你没有超出预期的分配。


So, for this part of the question, there is a surefire answer:

Why would malloc fails yet not return a NULL. Could this be possible, or the reason for the error message i am getting is else?

In Linux, by default the kernel interfaces for allocating memory almost never fail outright. Instead, they set up your page table in such a way that on the first access to the memory you asked for, the CPU will generate a page fault, at which point the kernel handles this and looks for physical memory that will be used for that (virtual) page. So, in an out-of-memory situation, you can ask the kernel for memory, it will "succeed", and the first time you try to touch that memory it returned back, this is when the allocation actually fails, killing your process. (Or perhaps some other unfortunate victim. There are some heuristics for that, which I'm not incredibly familiar with. See "oom-killer".)

Some of your other questions, the answers are less clear for me.

Why is this behaviour different when run under gdb and when without debugger?
It could be (just a guess really) that GDB has its own malloc, and is tracking your allocations somehow. On a somewhat related point, I've actually frequently found that heap bugs in my code often aren't reproducible under debuggers. This is frustrating and makes me scratch my head, but it's basically something I've pretty much figured one has to live with...

How do i fix this?

This is a bit of a sledgehammer solution (that is, it changes the behavior for all processes rather than just your own, and it's generally not a good idea to have your program alter global state like that), but you can write the string 2 to /proc/sys/vm/overcommit_memory. See this link that I got from a Google search.

Failing that... I'd just make sure you're not allocating more than you expect to.

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)