1. 程式人生 > >SPOJ:Just One Swap(統計&思維)

SPOJ:Just One Swap(統計&思維)

ans contain algorithm not star 一個數 positions swe osi

You are given an array of size N. How many distinct arrays can you generate by swapping two numbers for exactly once? The two selected numbers can be equal but their positions in the array must be different.

Input

The first line of the input contains a single integer T, denoting the number of test cases. Every test case starts with an integer N. The next line contains N integers, the numbers of the array.

Output

For each tescase output the answer in a single line.

Constraints:

1 <= T <= 5

1 <= Value of a number in the array <= 100000

2 <= N <= 100000

Example

Input:

1
5
2 3 2 3 3

Output:
7

You can generate the following arrays:

2 3 2 3 3

2 2 3 3 3

2 3 3 2 3

2 3 3 3 2

3 2 2 3 3

3 3 2 2 3

3 3 2 3 2

題意:問給定一個數論,問交換兩個位置上的數,可以變成多少個新的數組(重復的只統計一次)。

思路:先考慮變後與原來數論不同:對於每個位置,可以和與此數不同的位置交換,每一種合法交換統計了兩次,最後除二。

如果某個數出現的次數大於1,則可以產生與原數論相同的數列。ans++;

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using
namespace std; const int maxn=100010; int a[maxn],num[maxn]; long long ans=0; int main() { int N,T,i,j; bool F; scanf("%d",&T); while(T--){ memset(num,0,sizeof(num)); scanf("%d",&N); ans=0; F=false; for(i=1;i<=N;i++){ scanf("%d",&a[i]); num[a[i]]++; } for(i=1;i<=N;i++){ if(num[a[i]]>1) F=true; ans+=(N-num[a[i]]); } ans>>=1LL; if(F) ans++; printf("%lld\n",ans); } return 0; }

SPOJ:Just One Swap(統計&思維)