IDEONE:http: //ideone.com/ uSqSq7
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
using namespace std;
struct node
{
int value, position;
bool left, right;
bool operator < (const node& a) const
{
return value < a.value;
}
};
int main()
{
int n;
cin >> n;
vector < node > a(n);
set < node > s;
for (auto &i: a)
{
cin >> i.value;
i.left=i.right=0;
}
a[0].position=1;
s.insert(a[0]);
for (int i=1; i<n; i++)
{
auto it=s.upper_bound(a[i]);
auto it2=it; --it2;
if (it==s.begin())
{
a[i].position=2*it->position;
s.insert(a[i]);
it->left=1;
}
else if (it==s.end())
{
a[i].position=2*(--it)->position+1;
s.insert(a[i]);
it->right=1;
}
else
{
if (it2->right==0)
{
a[i].position=2*it2->position+1;
s.insert(a[i]);
it2->right=1;
}
else
{
a[i].position=2*it->position;
s.insert(a[i]);
it->left=1;
}
}
}
for (auto i: a) cout << i.position << ' ';
}
Run Code Online (Sandbox Code Playgroud)
当我编译这段代码时,我得到了
error: assignment of member ‘node::right’ in read-only object
我认为这与constin有关bool operator <,但我无法摆脱它,因为有必要创建该集合.
Angelika Langer曾写过一篇关于此事的文章:Set Iterators是可变的还是不变的?.
您可以通过将订购的Node成员定义为非物质来解决此问题:setmutable
mutable bool left, right;
Run Code Online (Sandbox Code Playgroud)
就个人而言,我会考虑使用a将不可变部分映射到可变部分的设计map.