一个题目,求解决方法!!!!

a923478106 2012-03-19 09:43:00
有N(1<=N<=500000)对球,每对球的编号是相同的,现在,不小心,掉了一颗球,现在给你剩余所有(2*N-1)个球的编号,找出丢失球的编号!!!

输入:
3
2 4 5 4 5
输出:
2


要求,方法高效。

下面这个方法超时
#include<iostream>
#include<string>
#include<set>
#include<fstream>
using namespace std;

int main()
{
ifstream cin("a.txt");
int n,pairs;
multiset<int> mshoes;
int flag=0;

while(cin>>n)
{
if(n==0)
break;
for(int i=0;i<2*n-1;i++)
{
cin>>pairs;
multiset<int>::iterator it=mshoes.find(pairs);
if(it!=mshoes.end())
mshoes.erase(it);
else
mshoes.insert(pairs);
}
for(multiset<int>::iterator it=mshoes.begin();it!=mshoes.end();it++)
cout<<*it<<endl;
mshoes.clear();

}
getchar();
return 0;
}

下面这个方法,wrong anwser
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;

int main(int argc, char* argv[])
{
ifstream cin("a.txt");
int pair;
int temp;
while(cin>>pair)
{
if(pair == 0)
break;
vector<int> num;
for(int i=0; i<(2*pair-1); i++)
{
cin>>temp;
num.push_back(temp);
}
sort(num.begin(), num.end());
for(int j=0; j<(2*pair-1); j=j+2)
if(num[j] != num[j+1])
{
cout<<num[j]<<endl;
break;
}
}
return 0;
}
...全文
134 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
xinyuwang 2012-03-19
  • 打赏
  • 举报
回复
请教楼主为什么第二个是wrong呢?我运行结果正常啊。
xinyuwang 2012-03-19
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 a923478106 的回复:]

谢谢楼上各位,我解决了
[/Quote]
请教为什么第二个是wrong呢?
muyi66 2012-03-19
  • 打赏
  • 举报
回复
嗯,异或是个好办法
nice_cxf 2012-03-19
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 muyi66 的回复:]

如果直接用循环查找,时间复杂度太大了。

考虑先用快速排序,排好之后再用循环查找。这样应该更快。
[/Quote]
还排什么序,直接异或就完了
A^B^C^D^C^B^D=A后边无论顺序怎么变结果都是A
bluewanderer 2012-03-19
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 a923478106 的回复:]

回复5楼:

引用 5 楼 bluewanderer 的回复:

嗯... 挨个异或之后是几就是那个单的


能否举个例子
[/Quote]

6楼,两个相同的数异或之后是0,所以所有成对的都互相抵消了,只剩下那个单的
a923478106 2012-03-19
  • 打赏
  • 举报
回复
谢谢楼上各位,我解决了
muyi66 2012-03-19
  • 打赏
  • 举报
回复
如果直接用循环查找,时间复杂度太大了。

考虑先用快速排序,排好之后再用循环查找。这样应该更快。
a923478106 2012-03-19
  • 打赏
  • 举报
回复
回复5楼:

[Quote=引用 5 楼 bluewanderer 的回复:]

嗯... 挨个异或之后是几就是那个单的
[/Quote]

能否举个例子
nice_cxf 2012-03-19
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 a923478106 的回复:]

回复2楼:

能否说的具体点
[/Quote]
还要具体?
int nRet =0 ;
for (int i =0;i<2*n-1;i++)
{
nRet ^=ballNo[i];
}
return nRet;
n是输入,ballNo[i]对应球序号的int数组
bluewanderer 2012-03-19
  • 打赏
  • 举报
回复
嗯... 挨个异或之后是几就是那个单的
a923478106 2012-03-19
  • 打赏
  • 举报
回复
回复2楼:

能否说的具体点
a923478106 2012-03-19
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 bluewanderer 的回复:]

内存限制多大,radix sort倒是可以O(N),缺点空间复杂度也是O(N),而且感觉应该还能更快
[/Quote]

65536KB。

我用了排序的方法,但是,却是wrong anwser
nice_cxf 2012-03-19
  • 打赏
  • 举报
回复
直接异或
bluewanderer 2012-03-19
  • 打赏
  • 举报
回复
内存限制多大,radix sort倒是可以O(N),缺点空间复杂度也是O(N),而且感觉应该还能更快

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧