题解 | #还原魔方#
还原魔方
https://ac.nowcoder.com/acm/contest/27740/A
1.每个数对p取模放入v数组
2.无序变有序sort
3.找每个数的另一半 其中两个数的和一定会小与2p 我们找p-v[i] and 2p-v[i]; 位置减一防止其位置为-1 第一个我们加个判断pos>1
lower_bound 返回第一个大于等于 x 的数的地址/迭代器
upper_bound 返回第一个大于 x 的数的地址/迭代器
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,p;
cin>>n>>p;
vector<int>v;
for(int i = 0; i < n; i++)
{
int a;
cin>>a;
v.push_back(a%p);
}
sort(v.begin(),v.end());
int ans = 0;
for(int i = 0; i < n; i++)
{
int temp=p-v[i];
int pos = lower_bound(v.begin(),v.end(),temp) - v.begin() - 1;
if(pos>0&&pos!=i)ans = max((v[pos]+v[i])%p,ans);
temp += p;
pos = lower_bound(v.begin(),v.end(),temp) - v.begin() - 1;
if(pos!=i)ans = max((v[pos]+v[i])%p,ans);
}
cout<<ans<<endl;
return 0;
}