hdu_2668 Daydream O(n)求最长不重复子串

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2668

Daydream

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 1658    Accepted Submission(s): 490

Problem Description
Welcome to 2009 HDU Girl’s Cup, bless you will happy in it. Every girl are beautiful if you use you heart to feel. Every corner in the world will colourful and energetic by several girls standing. If you boy, a normal bay, I believe that you will try to watch when a beautiful girl passing you and you will nervous if a girl watching you just when you are watching her. hdu_2668 Daydream  O(n)求最长不重复子串 Now give you a surprise that may be never happy in the real time. Millions of PLMM stand in a line and facing you(^_^). They are dress colourful clothings. You should to find out a maximal subline PLMM that their clothing color are all different.
 
Input
The input contains multiple test cases. Each case first give a integer n expressing many many girls stand in line.(n<=10000000) Next line a string including n character, each character standing one girls’s clothing color.
 
Output
Output one integer the numbers of maximal subline PLMM that their clothing color are all different and the line's begin and end (based from 0). If their are more answer, print the begin smallest.
 
Sample Input
3 abc 5 aaaba 8 hdugirls
 
Sample Output
3 0 2 2 2 3 8 0 7
 
Author
yifenfei
 
题意:  O(n)求最长不重复子串,注意,这里的字符没有说是从a~z所以要取所有的ASCII(0~127   因为是7位表示的)设置一个数组mp[127]表示对应字符出现在当前时期的前一个位置是哪里l ,r 表示扫描的左右端点,如果输入的ch 对应的mp[ch]>l 就要修改l的值为mp[ch]+1,这种O(n)的思想要注意的是输入输出容易超时,每次都申请读入是很耗费时间的,所以,开一个10000000的数组,直接用gets(s); 读入即可,下面是我超时的代码和ac的代码,可以看到真的有卡scanf的题、
 #include<cstring>
#include <cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = ;
char s[];
int mp[N];
int main()
{
int n,l,r,curL, len; //l, r 是最终答案
while(~scanf("%d",&n))
{
getchar();
gets(s);
len = ;
curL = ;
memset(mp,-,sizeof(mp));
for(int i = ; i < n; i++)
{
if(mp[s[i]] >= curL)
{
if(i-curL > len)
{
len = i-curL;
l = curL, r = i-;
}
curL = mp[s[i]]+;
}
mp[s[i]] = i;
}
if(n-curL > len) {
len = n-curL;
l = curL, r = n-;
}
printf("%d %d %d\n", len, l, r);
}
return ;
}

下面是超时代码:

 #include<cstdio>
#include<cstring>
using namespace std;
const int N = ;
int vis[N]; int main()
{
int n;
while(~scanf("%d",&n))
{
memset(vis,-,sizeof(vis));
char ch;
getchar();
int l=, r=-;
int len = ;
int ansl = ;
int ansr = -;
int anslen = ;
for(int i = ; i < n; i++)
{
scanf("%c",&ch);
int tm = ch-'a';
//printf("tm = %d\n",tm);
r++;
len++;
if(vis[tm]==-){
//vis[ch] = i;
if(len>anslen){
ansl = l;
ansr = r;
anslen = len;
}
}
while(vis[tm]!=-){
for(int j = ; j < ; j++)
{
if(vis[j]==l) {
vis[j] = -;
l++;
len--;
break;
}
}
if(len>anslen){
ansl = l;
ansr = r;
anslen = len;
}
}
vis[tm] = i;
}
printf("%d %d %d\n",anslen,ansl,ansr);
}
return ;
}
上一篇:前端js,css文件合并三种方式,bat命令


下一篇:Android Activity的onSaveInstanceState() 和 onRestoreInstanceState()方法: