我遇到了一个奇怪的问题。添加两个绝对(正)值时,我得到一个负值。我试图通过编码来解决这个练习(链接:https://www.codingame.com/ide/puzzle/network-cabling)。
我试过调试,我得到了这个:
X[i]: 19715507 X[j]: 938059973 // This one is good
temp: 918344466
Y[i]: 470868309 Y[j]: -816049599 //Something is wrong here
temp: -2089704922
这段代码可能不是一个很好的解决方案,我需要改进它,但我仍然无法弄清楚为什么价值是负面的。
请帮忙。
谢谢。
代码:
int main()
{
int N;
int X[100000];
int Y[100000];
cin >> N; cin.ignore();
for (int i = 0; i < N; i++) { //reading all input
cin >> X[i] >> Y[i]; cin.ignore();
}
int ilgis=0; //ilgis means length
for(int i=0; i<N-1; i++){ //"min" is set to a very high value
//so it could find a lower value later
// "not the best solution"
int min=99999999999999999999; //shortest distance between houses
for(int j=0; j<N; j++){ // here I am trying to find the shortest
// distance from one house to another
if(j!=i){ //I can't count distance from the same house because
// it would be 0
int temp=0;
//counting the distance differently if the
//value is negative or positive
if(X[i]<=0&&X[j]<=0) temp+=abs(abs(X[i])-abs(X[j]));
else if(X[i]<=0&&X[j]>=0) temp+=abs(X[i])+abs(X[j]);
else if(X[i]>=0&&X[j]>=0) temp+=abs(X[i]-X[j]);
else if(X[i]>=0&&X[j]<=0) temp+=(X[i])+abs(X[j]);
//same with y axis
if(Y[i]<=0&&Y[j]<=0) temp+=abs(abs(Y[i])-abs(Y[j]));
else if(Y[i]<=0&&Y[j]>=0) temp+=abs(Y[i])+abs(Y[j]);
else if(Y[i]>=0&&Y[j]>=0) temp+=abs(Y[i]-Y[j]);
else if(Y[i]>=0&&Y[j]<=0) temp+=(Y[i])+abs(Y[j]);
if(min>temp) min=temp;
}
} //if i found the shortesst distance between
//houses I add that value to overall distance
// and continue until all houses are checked
ilgis+=min;
}
cout<<ilgis<<endl;
}
练习的输入:
8
-28189131 593661218
102460950 1038903636
938059973 -816049599
-334087877 -290840615
842560881 -116496866
-416604701 690825290
19715507 470868309
846505116 -694479954
答案 0 :(得分:2)
int
的最大值为2147483647(假设int
具有32位宽度,则为2 ^ 31-1)。您可以使用
std::numeric_limits<int>::max();
您可能希望min
使用此值。此外,还可以使用long long
作为计算类型。