https://blog.csdn.net/JiangHxin/article/details/104032351
import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.Scanner; import java.util.concurrent.LinkedBlockingDeque; public class Main { static int a[] =new int[2005]; static int mod; public static int gets(String s) {//把字符转化为十进制数 int ans=0; int n=s.length(); for(int i=0;i<n;i++) { ans=ans*26+s.charAt(i)-'A'; ans%=mod;//防止数据溢出 } return ans; } public static void main(String[] args) { Scanner cin=new Scanner(System.in); String s=cin.next(); mod=cin.nextInt(); int n=s.length(); // System.out.println(n); int ans=gets(s); if(ans==0) { System.out.println("0 0"); return ; } a[n-1]=1; for(int i=n-2;i>=0;i--) {//每一位的权值 a[i]=26*a[i+1]%mod; //System.out.println(a[i]); } for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) { int res=(s.charAt(i)-s.charAt(j))*a[j]+(s.charAt(j)-s.charAt(i))*a[i];//变化值 if( (res+ans+mod)%mod==0) { System.out.println(++i +" "+ ++j); return ; } } System.out.println("-1 -1"); } }
#include<cstdio> #include<cstring> #include<string> #include<cmath> using namespace std; char s[2005]; int a[2005]; int mod; int ge(char s[]) { int ans=0; int len=strlen(s); for(int i=0;i<len;i++) { ans=ans*26+s[i]-'A'; ans%=mod; } return ans; } int main() { scanf("%s",s); scanf("%d",&mod); int ans=ge(s); if(ans==0) { printf("0 0 "); return 0; } int n=strlen(s); a[n-1]=1; for(int i=n-2;i>=0;i--) { a[i]=a[i+1]*26%mod; } for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { int res=(s[i]-s[j])*a[j]+(s[j]-s[i])*a[i]; if((res+ans+mod)%mod==0) { // printf("!!!!!!! "); printf("%d %d ",++i,++j); return 0; } } } printf("-1 -1 "); return 0; }