CodeForces 615C: Running Track LCP

传送门

题目描述

将所给的串反转,所求串分别与正串,反串比较,选择最优的记录

分析

预处理出正反字符串的lcp,然后暴力比较即可

代码

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
#define debug(x) cout<<#x<<":"<<x<<endl;
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 3010;
char a[N],b[N];
int l1,l2;
int lcp1[N][N],lcp2[N][N];
queue<PII> ans;

void LCP(){
    
    
	for(int i = l2;i;i--)
		for(int j = l1;j;j--)
			if(b[i] == a[j]) lcp1[i][j] = lcp1[i + 1][j + 1] + 1;
	for(int i = l2;j;i--)
		for(int j = 1;j <= l1;j++)
			if(b[i] == a[j]) lcp2[i][j] = lcp2[i + 1][j - 1] + 1;
}

int main(){
    
    
    scanf("%s",a + 1);
    getchar();
    scanf("%s",b + 1);
    l1 = strlen(a + 1);
    l2 = strlen(b + 1);
    LCP();
    bool flag = true;
    for(int i = 1;i <= l2;i++){
    
    
    	int maxv = 0;
    	int x,y;
    	for(int j = 1;j <= l1;j++)
    		if(lcp1[i][j] > maxv){
    
    
    			maxv = lcp1[i][j];
    			x = j;
    			y = j + maxv - 1;
    		}
    	for(int j = l1;j;j--)
    		if(lcp2[i][j] > maxv){
    
    
    			maxv = lcp2[i][j];
    			x = j;
    			y = j - maxv + 1;
    		}
    	cout << i << endl;
    	if(maxv == 0){
    
    
    		flag = false;
    		break;
    	}
    	ans.push({
    
    x,y});
    	i += maxv - 1;
    }
    if(!flag){
    
    
    	puts("-1");
    	return 0;
    }
    printf("%d\n",ans.size());
    while(ans.size()){
    
    
    	auto t = ans.front();
    	ans.pop();
    	printf("%d %d\n",t.first,t.second);
    }
    return 0;
}

/**
*  ┏┓   ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃       ┃
* ┃   ━   ┃ ++ + + +
*  ████━████+
*  ◥██◤ ◥██◤ +
* ┃   ┻   ┃
* ┃       ┃ + +
* ┗━┓   ┏━┛
*   ┃   ┃ + + + +Code is far away from  
*   ┃   ┃ + bug with the animal protecting
*   ┃    ┗━━━┓ 神兽保佑,代码无bug 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┓┏━┳┓┏┛ + + + +
*    ┃┫┫ ┃┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/


猜你喜欢

转载自blog.csdn.net/tlyzxc/article/details/112756693