I made weight directed graph, just like this
6
0 3 4 INFINITY INFINITY INFINITY
INFINITY 0 INFINITY 7 INFINITY INFINITY
INFINITY 3 0 5 11 INFINITY
INFINITY INFINITY INFINITY 0 6 3
INFINITY INFINITY INFINITY INFINITY 0 4
INFINITY INFINITY INFINITY INFINITY INFINITY 0
at first, I used some integer value to express infinity like 99 or 20000. but when I find it is wrong, v5 -> v4 must be express infinity but some integer value is expressed.
ex : Shortest Path from v2 to v3 : v2 v3 (length : 200000)
is there any infinity value for integer?
friend of mine says ~(1<<31) but it doesn't work
There is no representation of infinity in C. infinity, if available; else to a positive constant of type float that overflows at translation time.
Setting an int Infinity: Integers are inherently finite; that is why we cannot define them to a right infinity. The nearby value that we can get is by initializing an “int” to its extreme value. The closest we can get by setting a variable to the maximum value that is double “a = std: numeric_limits<int>:: max();”.
With integers, there is no value that can represent infinity. Instead, it will set it to the largest value that an int can represent. If int happens to be a 32-bit integer, then INT_MAX == 2147483647 .
Unlike floating-point types, integer types don't have a standard value for infinity. If you have to have one, you'll have to pick a value yourself (e.g. INT_MAX
) and correctly handle it throughout your code. Note that if you do this, you can use the special value in assignments and comparisons, but not in arithmetic expressions.
Infinity doesn't exist for integers. What your friend suggested was the biggest number in a 32 bit signed integer, but that still is not infinity. That also introduces the possibility of overflow if you add it to something (for example in shortest path), you actually might end up getting a smaller number. So don't do it.
The proper way to do it, is to handle infinity case by case. Use a flag for infinity, for example that same ~(1<<31)
, or perhaps even better, -1
and in your code, whenever you want to add two values, check if either of them is equal to this flag (equal to infinity), set the result to infinity without actually doing any summations. Or when you are checking if one value is smaller than another, check if one is equal to this flag (equal to infinity), then the other is definitely smaller, again without actually doing the comparison.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With