Choosing Symbol Pairs
http://codeforces.com/problemset/problem/50/B
Time Limit:2000MS Memory Limit:262144KB 64bit IO Format:%I64d & %I64u
Description
There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that
1. 1 ≤ i, j ≤ N
2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
Input
The single input line contains S, consisting of lowercase Latin letters and digits. It is guaranteed that string S in not empty and its length does not exceed 105.
Output
Print a single number which represents the number of pairs i and j with the needed property. Pairs (x, y) and (y, x) should be considered different, i.e. the ordered pairs count.
Sample Input
Input
great10
Output
7
Input
aaaaaaaaaa
Output
100
多亏大神指点 离歌笑orz http://blog.csdn.net/yuanhanchun
大神在这道题的时候用了pow(x,y)函数,避免了这种情况的发生,详见代码
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char s[100004];
int main()
{
double ans,flag;
int l,i;
while(scanf("%s",s)!=EOF)
{
l=strlen(s);
sort(s,s+l);
ans=0;
flag=0;
for(i=1;i<l;i++)
if(s[i]!=s[i-1])
{
ans+=(flag-i)*(flag-i);
//刚开始flag用了int型,虽说flag控制在10^5以内不会超限,但乘积却有超出int的可能,虽然是加到double上,但在做乘法时已经出错了
flag=i;
}
ans+=(flag-i)*(flag-i);
printf("%.0lf\n",ans);
}
return 0;
}
另:
#include<stdio.h>
#include<string.h>
int t[125];
int main()
{
int i,l;
char s[100004];
while(scanf("%s",s)!=EOF)
{
l=strlen(s);
memset(t,0,sizeof(t));
for(i=0; i<l; i++)
{
t[s[i]]++;
}
double ans=0;
for(i='0'; i<='z'; i++)
{
ans+=(double)t[i]*t[i];
}
printf("%.0lf\n",ans);
}
return 0;
}