您的位置:首页 > 编程语言 > C语言/C++

OJ平台中的一个数组初始化问题

2016-09-06 23:01 316 查看
首先从一道ACM简单题说起:

问题 B: Friendship of Mouse

时间限制: 1 Sec 内存限制: 64 MB

提交: 24 解决: 15

[提交][状态][讨论版]

题目描述

Today in KBW, N mice from different cities are standing in a line. Each
city is represented by a lowercase letter. The distance between adjacent mice (e.g. the 1st and the 2nd mouse, the N−1th and the Nth mouse, etc) are exactly 1. Two mice are friends if they come from the
same city.

The closest friends are a pair of friends with the minimum distance. Help us find that distance.

输入

First line contains an integer T, which indicates the number of test cases.

Every test case only contains a string with length N, and the ith character of the string indicates the
city of ith mice.

⋅ 1≤T≤50.

⋅ for 80% data, 1≤N≤100.

⋅ for 100% data, 1≤N≤2000.

⋅ the string only contains lowercase letters.

输出

For every test case, you should output "Case #x: y", where x indicates the case number and counts from 1 and y is the result. If there are no mice in same
city, output −1 instead.

样例输入

2
abcecba
abc

样例输出

Case #1: 2
Case #2: -1


题目大意:给出一个全部由小写字母组成的字符串,计算相同字母间的距离(认为相邻字母距离为1),求出最短的相同字母距离,若没有相同字母,则输出-1

解题思路:用一个数组记录26个字母的位置信息,每次读到一个字母的时候即更新该字母的位置信息,然后计算距离之差,保存在另外一个数组中,这样得到的数组中保存的都是相同字母的距离,对该数组扫描一遍,找出最小值即可,这样做可以达到O(n)的复杂度。

AC代码:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int main()
{
int n;
int index=1;
int minn=0;
bool flag=false;
int re[10010];
int loc[100];                    //开始时我在此处进行数组的初始化,写成了int loc[100] = {0};
cin>>n;
for(int j=1;j<=n;j++)
{
index=1;
memset(loc,0,sizeof(loc));
memset(re,-1,sizeof(re));
char input[10010];
cin>>input;
for(int i=0;i<strlen(input);i++)
{
//  cout<<input[i]-'a'<<endl;
if(loc[input[i]-'a']==0)
{
loc[input[i]-'a'] = index;
re[index] = -1;
index++;
}
else
{
re[index] = index-loc[input[i]-'a'];
loc[input[i]-'a'] = index;
index++;
}
}
minn = 10000;
flag = false;
for(int i=1;i<10010;i++)
{
if((re[i]!=-1)&&(re[i]<minn))
{
minn = re[i];
flag = true;
}
}
if(flag)cout<<"Case #"<<j<<": "<<minn<<endl;
else cout<<"Case #"<<j<<": "<<-1<<endl;
}
return 0;
}


开始时,我在声明数组的时候即进行初始化,写成:int loc[100] = {0},然后提交代码之后,OJ平台给出的判题结果是RuntimeError……检查了好多遍,没有发现数组越界的地方,晕……后来怀疑是否是这个初始化的问题,于是将这行代码改成了:int loc[100];结果代码立即通过了!所以就是这个初始化造成了数组越界。然而后来上网查资料发现类似int loc[100] = {0}的写法确实是将100个元素均初始化为0,但是在OJ平台判题的时候显然不是这么认为的,目前还没找到理论依据,但是感觉应该是我自己用的编译器和OJ平台所用的编译器所用的C语言标准不同造成的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 C语言