您的位置:首页 > 其它

CodeForces 501 E.Misha and Palindrome Degree(组合数学)

2018-01-09 21:09 417 查看
Description

给出一个长度为n的序列ai,定义该序列的回文度为区间(l,r)的对数,其中l,r需要满足1≤l≤r≤n且对al,...,ar重排之后该序列是回文序列

Input

第一行为一整数n表示序列长度,之后输入n个整数ai表示该序列(1≤n≤105,1≤ai≤n)

Output

输出该序列的回文度

Sample Input

3

2 2 2

Sample Output

6

Solution

统计每个数字出现的次数num[i],如果num[i]中有超过一个奇数则不可能回文,方案数为0,否则首先从两端开始往中间找已经回文的最长长度pos,那么只要区间左右端点取在两端这pos个位置均可回文,方案数pos2, 然后分别考虑两个端点还可以往中间走多远,只需统计已经使用的数字个数,只要其不超过该数字个数的一半就可以继续走,假设左边还可以走len1,那么右端点取后pos个位置均可,方案数len1⋅pos,同理如果右边还可以走len2,那么左端点取前pos个位置均可,方案数len2⋅pos,总方案数pos⋅(pos+len1+len2)

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=100005;
int n,a[maxn],num[maxn],use[maxn];
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)scanf("%d",&a[i]),num[a[i]]++;
int flag=0;
for(int i=1;i<=n;i++)
if(num[i]&1)flag++;
if(flag>1)printf("0\n");
else
{
int pos=0;
for(int i=1;i<=n/2;i++)
if(a[i]!=a[n-i+1])
{
pos=i;
break;
}
else num[a[i]]-=2;
if(!pos)printf("%I64d\n",(ll)n*(n+1)/2);
else
{
int cnt=0;
for(int i=pos;i<=n;i++)
{
use[a[i]]++;
if(2*use[a[i]]>num[a[i]])
{
if(i<n-i+1||i==n-i+1&&num[a[i]]%2==0||a[i]!=a[n-i+1])break;
}
cnt++;
}
memset(use,0,sizeof(use));
for(int i=n-pos+1;i>=1;i--)
{
use[a[i]]++;
if(2*use[a[i]]>num[a[i]])
{
if(i>n-i+1||i==n-i+1&&num[a[i]]%2==0||a[i]!=a[n-i+1])break;
}
cnt++;
}
printf("%I64d\n",(ll)pos*(pos+cnt));
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: