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
给出一个长度为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; }
相关文章推荐
- 2018.2.2【 CodeForces - 501B 】解题报告(STL,map,字符串处理)
- Misha and Permutations Summation - CodeForces 501 D 树状数组
- codeforces 501 C,D,E
- codeforces 501 C. Misha and Forest (思维)
- 【codeforces 501 C Misha and Forest】
- codeforces 501B B. Misha and Changing Handles
- codeforces 501 B Misha and Changing Handles 【map】
- Codeforces 501B:Misha and Changing Handles(略水+小小技巧)
- Problem - 501B - Codeforces(string+map)
- Codeforces 501 B - Misha and Changing Handles
- Codeforces 69E Subsegments (SET/线段树)
- CodeForces 595A
- codeforces 721E. Road to Home
- Codeforces Ilya and Matrix
- Codeforces 500B - New Year Permutation(最短路)
- codeforces 766 B
- Codeforces 839A Arya and Bran (模拟)
- CodeForces - 165C Another Problem on Strings —— 前缀和字串
- 【CodeForces】[675A]Infinite Sequence
- CodeForces 733B Parade