题目
Problem C: An Interesting Problem
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 48 Solved: 11
[ Submit][ Status][ Web Board]
Description
(如(1 1 2)有3种分别是(1,1,2)(1,2,1)(2,1,1))请帮GG解决这个问题。
Recently Mr GG was studying a math problem. He would like to know, given an array and then you can arbitrarily exchange two different numbers, ask a total of several different combinations can be made
(1, 1, 2) (2, 1, 1)) Please help GG solve this problem
Input
第一行输入t表示t组数据,然后输入t组数据每组数据输入一个n(1<=n<=100000),接下来一行输入n个数,每个数不超过100000
The first line of input t that t group of data, and then enter the t group of data output data for each group of a n (1 <= n <= 100000), the next line input n number, each number does not exceed 100000
Output
输出总共的几种组合
Output a total of several combinations
Sample Input
1
5
3 1 1 3 3
Sample Output
7
HINT
解题思路:
例如(1,1,2)中,1只有和2交换才能构成新的组合。而(1,1,2)这个数组中有两个1,所以每个1都和2交换一次,构成两个不同的组合,再加上原本的组合(1,1,2),所以一共有三种。
综上所述,我们要做的操作如下:
1.记录总的元素各数为sum//sum=n;
2.定义num[100001]。num[i]表示第数字i出现了几次。
3.最后答案为ans,初始化为1(因为一开始输入的那个顺序就是一种组合)
4.公式:ans+=num[i]*(sum-num[i]);sum-=num[i]
代码:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int num[100001],i;
int t,n,temp;
long long sum,ans;//ans要定义为long long不然会超时
cin>>t;
while(t--)
{
memset(num,0,sizeof(num));
ans=1;
cin>>n;
sum=n;
while(n--)
{
cin>>temp;
num[temp]+=1;
}
for(i=0;i<=100000;i++)
{
ans+=num[i]*(sum-num[i]);
sum=sum-num[i];
}
cout<<ans;
if(t!=0)cout<<endl;//最后一次输出不输出空格
}
return 0;
}
遇到的坑:最开始把ans定义为int型,一直wrong answer。后来听学长建议改为long long就AC了