读书人

求问这个如何不能ac 有关问题出在那?

发布时间: 2013-09-24 10:59:52 作者: rapoo

求问这个怎么不能ac 问题出在那? 本人是新手
问题是这个:
Problem Description
Maybe there are 750,000 words in English and some words are prefix of other words, for example: the word "acm" can be treat as one prefix of "acmicpc". What's more, most of such pairs of words have relationship between them. Now give you a dictionary, your work is to tell me how many such pairs.


There may be other characters in the word, for example '_','-',and so on.
Pay attention that 'A' and 'a' are not the same character!
我的代码:#include <iostream>
#include <string.h>
using namespace std;

bool isProfix(char s1[],char s2[]){
int n1=strlen(s1);
int n2=strlen(s2);
bool isMatch=true;
int k=(n1>n2)?n2:n1;
for(int i=0;i<k;i++){
if(s1[i]!=s2[i]){
isMatch=false;
break;
}
}
return isMatch;
}
int count(char s1[],char s2[]){
bool my;
my=isProfix(s1,s2);
if(my){
return 1;
}else {
return 0;
}
}

int main(int argc, char *argv[]) {

char str[1000][33];
int n;int flag=0;int m;
cin>>m;
for(int j=0;j<m;j++){
cin>>n;
for(int i=0;i<n;i++){
cin>>str[i];
}
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
flag+=count(str[i],str[j]);
}
}
flag=(flag>11519)?flag%11519:flag;
cout<<flag<<endl;
}


return 0;
} 自己测试没问题 提交出现超时错误.....


[解决办法]
看了下你写的代码!
思路和算法都没什么问题。
1. 但是你定义的char str[1000][33];视乎不怎么合理。
你这个位置:cin>>str[i];是不是应该是:cin>>str[j][i];?
感觉后面用的str也有问题。
自己定义的二维数组,用的时候也应该用二维数组。
2. 还有你这个:flag=(flag>11519)?flag%11519:flag;我不是很懂。

[解决办法]
题目不是说有75万个单词么
我认为这个题要用链表理由:
1.节省空间
2.查找方便,有可能不止测试1组数据,不排序基本over
[解决办法]
1)忽略 _ 或者 -
2)前缀
3)大小写,不需要匹配
就这么多东西

步骤:

1)先按字母序排序,长串在后,因为是字典,什么都不要做,(已经排好了)
2)对每一个单词,求到最后一个字母改变共多少单词
3)匹配 ,如果大小写相同,是前缀
4)要加速,充分利用前面的结果



[解决办法]
lz程序不能AC的问题:
1. char str[1000][33]不够大
2. 没有排序
3. 每个CASE前没有清计数flag
4. 函数count、cin、cout的使用导致超时

如下修改可AC:

#include <iostream>
#include <string.h>
using namespace std;

bool isProfix(char s1[],char s2[]){
int n1=strlen(s1);
int n2=strlen(s2);
bool isMatch=true;
int k=(n1>n2)?n2:n1;
for(int i=0;i<k;i++){
if(s1[i]!=s2[i]){
isMatch=false;
break;
}
}
return isMatch;
}
int count(char s1[],char s2[]){
bool my;
my=isProfix(s1,s2);
if(my){
return 1;
}else {
return 0;
}
}

int cmp(const void *str1, const void *str2)//加
{
return strcmp((char *)str1, (char *)str2);
}

int main(int argc, char *argv[]) {

static char str[50000][33];//char str[1000][33];
int n;int flag=0;int m;
scanf("%d", &m);//cin>>m;
for(int j=0;j<m;j++){
scanf("%d", &n);//cin>>n;
for(int i=0;i<n;i++){
scanf("%s", str[i]);//cin>>str[i];
}
qsort(str, n, sizeof(str[0]), cmp);//加
flag = 0;//加
for(int i=0;i<n;i++){


for(int j=i+1;j<n;j++){
if (isProfix(str[i],str[j])) flag++; else break;//flag+=count(str[i],str[j]);
}
}
flag=(flag>11519)?flag%11519:flag;
printf("%d\n", flag);//cout<<flag<<endl;
}


return 0;
}

读书人网 >C++

热点推荐