About the choice of infinite mass

Source: Internet
Author: User

When solving a problem, you usually have a situation where you are set to infinity. This time is usually set with 0x7fffffff, he is the computer 32-bit integer maximum number, the equivalent of Int_max. But in many cases this setting is not optimal and can lead to bugs because we sometimes want infinity + infinity = infinity, For example, in the prim algorithm or the Dijstra algorithm on the edge of the slack operation, this time Int_max arbitrarily add a number will overflow, resulting in a wrong result.

In fact, the other number 0x3f3f3f3f decimal is 1061109567, which is the same order of magnitude as 0x7fffffff. We use the 0x3f3f3f to replace the 0x7fffffff can satisfy infinity and infinity is still infinite conditions, so as to avoid catastrophic errors. In addition 0x3f3f3f can also use the Memset function to bulk assign values, such as to set the array dis[] to infinity:

memset (dis,0x3f,sizeof (dis));

if the array dis is a long long, the above statement sets the DIS to 4557430888798830399, and if the dis is of type int, the above statement sets the dis to 1061109567 whether in long or int, Two infinite and will not explode. The above 0x3f is a byte 0x3f3f3f3f altogether there are four such bytes. In general, 0X3F3F3F3F is a good choice for setting infinity.              

About the choice of infinite mass

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.