【发布时间】:2019-09-04 10:30:26
【问题描述】:
我试图在这里解决问题-https://www.codechef.com/APRIL19B/problems/FENCE 并将数组初始化为 0,但是当我尝试使用 n=4 和 m=4 访问 arr[0][4] 处的值时,它会打印一个垃圾价值。
我尝试使用向量进行初始化,认为我在初始化数组时犯了一些错误,它适用于示例测试用例,但仍然出现分段错误。
这是我的代码 -
#include<bits/stdc++.h>
#include <iostream>
using namespace std;
int main() {
// your code goes here
int t;
cin>>t;
while(t--){
long long n,m,k,res=0;
cin>>n>>m>>k;
//vector<vector<long long>> arr(n+2,vector<long long>(m+2,0));
long long arr[n+2][m+2]={0};
long long vec[k][k];
for(unsigned int it=0;it<k;it++){
int t1,t2;
cin>>t1>>t2;
arr[t1][t2]=1;
vec[it][0]=t1;
vec[it][1]=t2;
}
cout<<"values:"<<arr[1][4]<<endl;
for(unsigned int itr =0;itr<k;itr++){
int j = vec[itr][0];
int i = vec[itr][1];
//cout<<i<<" "<<j<<endl;
res+=4-(arr[i-1][j]+arr[i+1][j]+arr[i][j-1]+arr[i][j+1]);
}
cout<<res<<endl;
}
return 0;
}
编辑: 样本输入为:
Example Input
2
4 4 9
1 4
2 1
2 2
2 3
3 1
3 3
4 1
4 2
4 3
4 4 1
1 1
Example Output
20
4
约束:
1≤T≤10
1≤N,M≤10^9
1≤K≤10^5
1≤r≤N
1≤c≤M
the cells containing plants are pairwise distinct
我希望第一个测试用例的输出为 20,但会得到垃圾值。
【问题讨论】:
-
由于程序限制,
arr或vec很容易超过可用的自动内存。标准 C++ 也不支持可变长度数组的原因之一。考虑改用matrix class like this。 -
也不要包含
bits/stdc++.h或使用using namespace std,它们是非常糟糕的做法。绝对不要使用long long,因为你存储的只是一个布尔值。 -
#include<bits/stdc++.h>真正有趣的是<iostream>也包括在内。这暗示了一点Cargo Cult programming。bits/stdc++.h是一个特定于实现的头文件,旨在通过包含整个标准库来帮助预编译头文件。一些人认为这是一种避免必须包含他们需要包含的内容的方法,结果导致编译速度较慢且不可移植的代码。不是特别好的想法。 -
此外,始终检查用户输入的一致性(例如 t1 和 t2 小于 k)。
-
@JeJo,问题的限制阻止了这一点。这里是约束 1≤T≤10 1≤N,M≤109 1≤K≤105 1≤r≤N 1≤c≤M