B. Making a String
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:
the i-th letter occurs in the string no more than ai times;
the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.
Input
The first line of the input contains a single integer n (2 ≤ n ≤ 26) — the number of letters in the alphabet.
The next line contains n integers ai (1 ≤ ai ≤ 109) — i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.
Output
Print a single integer — the maximum length of the string that meets all the requirements.
Sample test(s)
input
3
2 5 5
output
11
input
3
1 1 2
output
3
Note
For convenience let’s consider an alphabet consisting of three letters: “a”, “b”, “c”. In the first sample, some of the optimal strings are: “cccaabbccbb”, “aabcbcbcbcb”. In the second sample some of the optimal strings are: “acc”, “cbc”.
题意:
不难理解,题目大意就是说一组字符串在满足以下两个条件下能组成的最大长度:①第i个字符的个数在字符串中不能超过ai次;②每个字符在字符串中出现的次数必须不同。
思路:
其实这道题讲思路不如直接上代码来的直接,但是还是讲讲吧23333…把每个字符出现的个数放到一个set中,然后当每个字符出现的个数与set中出现的某个字符的个数相同时,则当前字符数-1。但是注意有两个坑:①当每个字符的个数str[i]次小于0时,不再继续减少;②当每个字符的个数str[i]次与其他字符有相等时候,要继续减少个数。
代码:
#include<bits/stdc++.h>
using namespace std;
long long str[33];
set<long long>st;
int main()
{
int n;
while(cin>>n)
{
st.clear();
for(int i = 0; i < n; i++)
cin>>str[i];
sort(str,str + n);
long long cnt = str[0];
st.insert(str[0]);
long long flag = 1;
for(int i = 1; i < n; i++)
{
if(str[i] == str[i - 1])
{
if(str[i] - flag <= 0)
;
else
{
if(st.count(str[i] - flag) == 0)
{
cnt += (str[i] - flag);
st.insert(str[i] - flag);
}
else
{
bool tmp = true;
while(tmp)
{
flag++;
if(str[i] - flag < 0)
{
tmp = false;
break;
}
if(st.count(str[i] - flag) == 0)
{
cnt += (str[i] - flag);
st.insert(str[i] - flag);
tmp = false;
}
}
}
}
flag++;
}
else
{
if(st.count(str[i]) == 0)
{
st.insert(str[i]);
cnt += str[i];
}
else
{
bool tmp = true;
while(tmp)
{
flag++;
if(str[i] - flag < 0)
{
tmp = false;
break;
}
if(st.count(str[i] - flag) == 0)
{
cnt += (str[i] - flag);
st.insert(str[i] - flag);
tmp = false;
}
}
}
flag = 1;
}
}
cout<<cnt<<endl;
}
return 0;
}