题目描述
Misha has an array of n integers indexed by integers from 1 to n. Let's define palindrome degree of array a as the number of such index pairs (l, r)(1 ≤ l ≤ r ≤ n), that the elements from the l-th to the r-th one inclusive can be rearranged in such a way that the whole array will be a palindrome. In other words, pair (l, r) should meet the condition that after some rearranging of numbers on positions from l to r, inclusive (it is allowed not to rearrange the numbers at all), for any 1 ≤ i ≤ n following condition holds: a[i] = a[n - i + 1].
Your task is to find the palindrome degree of Misha's array.
解题思路
代码
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 using namespace std; 6 int n; 7 int a[100050],num[100050],oc[100050]; 8 inline void read(int &x){ 9 x=0; register char ch=getchar(); 10 while(ch<'0'||ch>'9')ch=getchar(); 11 while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar(); 12 } 13 int main(){ 14 read(n); 15 for(register int i=1;i<=n;i++){ 16 read(a[i]); 17 num[a[i]]++; 18 } 19 int tot=0; 20 for(register int i=1;i<=n;i++){ 21 if(num[i]&1)tot++; 22 } 23 //judge whether can be made to a palindrome 24 if((n%2==0&&tot)||(n%2&&tot>1)){ 25 cout<<0<<endl; 26 return 0; 27 } 28 29 int len=0; 30 for(register int i=1;i<=(n>>1);i++){ 31 if(a[i]!=a[n-i+1]){ 32 len=i; 33 break; 34 } 35 num[a[i]]-=2; 36 } 37 //if the array has already been a palindrome 38 if(len==0){ 39 cout<<(long long)n*(n+1)/2<<endl; 40 return 0; 41 } 42 //if the array is not a palindrome 43 int le=0,ri=0; 44 for(register int i=len;i<=n;i++){ 45 oc[a[i]]++; 46 if(oc[a[i]]*2>num[a[i]]){ 47 if(a[i]!=a[n-i+1])break; 48 if(i<n-i+1)break; 49 if(num[a[i]]%2==0&&i==n-i+1)break; 50 } 51 le++; 52 } 53 memset(oc,0,sizeof(oc)); 54 for(register int i=n-len+1;i>=1;i--){ 55 oc[a[i]]++; 56 if(oc[a[i]]*2>num[a[i]]){ 57 if(a[i]!=a[n-i+1])break; 58 if(i>n-i+1)break; 59 if(num[a[i]]%2==0&&i==n-i+1)break; 60 } 61 ri++; 62 } 63 cout<<(long long)len*(len+le+ri)<<endl; 64 }