1. 給出一個有N個數字(-1000..1000,N<=10^5)的環狀序列,求一個和最大的連續子序列。
http://www.cppblog.com/baby-fly/archive/2010/08/04/122213.aspx?Pending=true
來源於單調佇列的應用
#include<iostream>
#include<queue>
using namespace std;
#define INF 0x3fffffff
#define maxn 100010
int num[maxn],sum[maxn];
int main()
{
int T;
int N,K,n;
cin>>T;
while(T--)
{
cin>>N>>K;
sum[0]=0;
for(int i=1;i<=N;i++)
{
cin>>num[i];
sum[i]=sum[i-1]+num[i];
}
for(int i=N+1;i<N+K;i++)
{
sum[i]=sum[i-1]+num[i-N];
}
n=N+K-1;
deque<int> q;
q.clear();
int ans=-INF;
int start,end;
//[j-kj] 列舉以j結尾的區間,找[j-k,j]中sum最小的i
for(int j=1;j<=n;j++)
{
while(!q.empty() && sum[j-1]<sum[q.back()])
q.pop_back();
while(!q.empty() && q.front()<(j-K))
q.pop_front();
q.push_back(j-1);
if(sum[j]-sum[q.front()]>ans)
{
ans=sum[j]-sum[q.front()];
start=q.front()+1;
end=j;
}
}
cout<<ans<<" "<<start<<" "<<(end>N?end%N:end)<<endl;
}
}
2. 一道微軟的面試題
http://www.cnblogs.com/qsort/archive/2011/05/30/2063605.html 本著測試先行的原則 。。。 是啊,這得閒考慮多個情況後才編碼
#include <stdio.h>
#include <assert.h>
#include <string.h>
// Test cases for leading & trailing spaces.
char arr00[] = "hello_world";
char arr01[] = "hello world";
char arr02[] = " hello world";
char arr03[] = "hello world ";
char arr04[] = " hello world ";
// Test cases for consecutive spaces.
char arr05[] = "hello world";
char arr06[] = " hello world ";
// Test cases for spaces around new-lines.
char arr07[] = "hello \n world ";
char arr08[] = " hello world \n ";
char arr09[] = "\n hello world \n ";
// Corner cases
char arr10[] = " ";
char arr11[] = "\n";
char arr12[] = " \n ";
void filter_spaces(char *str, size_t len)
{
char *dst = str + len - 1;
char *curr = str + len - 1;
while (*curr == ' ' && curr >= str)
--curr; // remove trailing spaces;
if (curr < str) { // all spaces.
*str = '\0';
return;
}
int after_space = 0;
int around_newline = 0;
while (curr >= str) {
switch (*curr) {
case ' ':
if (after_space) { // a space followed by another space, omit it.
--curr;
} else if (around_newline) { // a space around a newline, omit it.
--curr;
} else {
after_space = 1;
*dst-- = *curr--;
}
break;
case '\n':
around_newline = 1;
if (after_space) { // remove last recorded space.
assert(*(dst + 1) == ' ');
++dst;
after_space = 0;
}
*dst-- = *curr--;
break;
default: // other chars
*dst-- = *curr--;
after_space = 0;
around_newline = 0;
break;
}
}
++dst;
if (*dst == ' ') // remove leading spaces.
++dst;
// now the filtered string size is ( (str + size) - dst + 1 ),
// including the trailing '\0'
memmove(str, dst, (str + len) - dst + 1);
}
#define TEST_STR(str) do {\
filter_spaces(str, strlen(str));\
printf(#str ": \"%s\"\n", str);\
} while(0);
int main(int argc, char *argv[])
{
TEST_STR(arr00);
TEST_STR(arr01);
TEST_STR(arr02);
TEST_STR(arr03);
TEST_STR(arr04);
TEST_STR(arr05);
TEST_STR(arr06);
TEST_STR(arr07);
TEST_STR(arr08);
TEST_STR(arr09);
TEST_STR(arr10);
TEST_STR(arr11);
TEST_STR(arr12);
return 0;
}