Educational Codeforces Round 94 (Rated for Div. 2) D. Zigzags

D. Zigzags

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

You are given an array a1,a2…ana1,a2…an. Calculate the number of tuples (i,j,k,l)(i,j,k,l) such that:

  • 1≤i<j<k<l≤n1≤i<j<k<l≤n;
  • ai=akai=ak and aj=alaj=al;

Input

The first line contains a single integer tt (1≤t≤1001≤t≤100) — the number of test cases.

The first line of each test case contains a single integer nn (4≤n≤30004≤n≤3000) — the size of the array aa.

The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n) — the array aa.

It's guaranteed that the sum of nn in one test doesn't exceed 30003000.

Output

For each test case, print the number of described tuples.

Example

input

Copy

2
5
2 2 2 2 2
6
1 3 3 1 2 3

output

Copy

5
2

Note

In the first test case, for any four indices i<j<k<li<j<k<l are valid, so the answer is the number of tuples.

In the second test case, there are 22 valid tuples:

  • (1,2,4,6)(1,2,4,6): a1=a4a1=a4 and a2=a6a2=a6;
  • (1,3,4,6)(1,3,4,6): a1=a4a1=a4 and a3=a6a3=a6.

思路1:从范围3000可以看出是n^2的算法,即两重循环,遍历j和k即可确定ai和al的值,也可确定i和l的范围,利用前缀和保存前i个数中a[i]的个数,再利用乘法原理计算情况个数。

#include<iostream>
#include<algorithm>
#include<cstring>
#define ll long long

using namespace std;

const int N = 3030;

int sum[N][N];
int a[N];

int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		int n;
		cin>>n;
		memset(sum, 0, sizeof sum);
		for(int i=1; i<=n; i++) 
		{
			cin>>a[i];
			for(int j=1; j<=n; j++) sum[i][j] = sum[i-1][j];//前i个数中值为j的个数 
			sum[i][a[i]]++;
		}
				
		long long ans = 0;
		
		for(int j=2; j<=n-2; j++)
			for(int k=j+1; k<=n-1; k++)
				ans += sum[j-1][a[k]] * (sum[n][a[j]] - sum[k][a[j]]);//前j-1个中a[i] = a[k]的i的个数乘以k+1~n中a[j] = a[i]可能的i的个数 
		cout<<ans<<endl;
	}
	return 0;
}

思路2:

i j k l
遍历 j 和 l ,用cnt数组记录 j 之前 ai 的出现个数,在遍历 l 时,用sum保存 j 和 l 之间ak和ai匹配的个数,如果aj==al,

ans+sum,即更新了aj==al情况下时,ak和ai的匹配个数.

#include<iostream>
#include<algorithm>
#include<cstring>
#define ll long long

using namespace std;

const int N = 3030;

int a[N];
int cnt[N];

int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		int n;
		cin>>n;
		for(int i=1; i<=n; i++) 
			cin>>a[i];
		memset(cnt, 0, sizeof cnt);
		long long ans = 0;
		for(int j=1; j<=n; j++)//记录j之前元素(a[i])出现个数 
		{
			int sum = 0;
			for(int l=j+1; l<=n; l++)
			{
				if(a[j] == a[l]) ans += sum;//ans加上i和k的匹配数 
				sum += cnt[a[l]];//sun加上a[k]在a[i]中出现的个数,即a[k]==a[i]的对数 
			}
			cnt[a[j]]++;
		}	
		cout<<ans<<endl;
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值