题意:给一个只含'U'和'D'的字符串,U表示向右走,D表示向左走。每个格子踩一次之后翻转(U变D,D变U),求从每个格子出发走多少步才能走到位置小于1或大于n。
分析:当在第i个格子的时候,我们假设初始位置是在i-1和i中间这条缝隙处,然后初始是向右走,然后我们会得到一个区间(l,r]表示我们最左走到l+1,最右走到r,然后最终又回到i。这时候我们左右的转折点是左边的'U'和右边的'R',我们分别统计一下两边转折点的个数,然后每次进行调整即可。第i个点的区间(l,r]可以用从第i-1个转移过来,很容易知道两个指针都是递增的O(n)。
代码:
#include<map>
#include<set>
#include<stack>
#include<cmath>
#include<queue>
#include<bitset>
#include<math.h>
#include<vector>
#include<string>
#include<stdio.h>
#include<cstring>
#include<iostream>
#include<algorithm>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
typedef double db;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
const db eps=1e-5;
const int N=1e6+10;
const int M=4e6+10;
const ll MOD=1000000007;
const int mod=1000000007;
const int MAX=1000000010;
const double pi=acos(-1.0);
char s[N];
int main()
{
ll n,x=0,y=0,u=0,d=0,l=0,r=0;
scanf("%I64d%s", &n, s+1);
for (int i=1;i<=n;i++) {
x+=2*u;y-=2*d;
if (s[i-1]=='U') u++,x+=2;
if (s[i-1]=='D') d--,y+=2;
while (u>=d&&r<n) if (s[++r]=='D') d++,y+=2*(r-i);
while (u>d&&r==n) if (s[++l]=='U') u--,x-=2*(i-l);
if (u==d) printf("%I64d ", x+y+n-i+1);
else printf("%I64d ", x+y+i);
}
return 0;
}