hdu-2095 find your present(2)
阿新 • • 發佈:2019-04-24
using 題目 res pytho href key-value void bubuko 一個數
題目描述如下:
方法一:
位運算
原理:兩個相同的數x,x進行按位與操作,即x^x,結果為0,某個數y與0按位與則結果為原數,即y^0=y;
so,某個數y,遇到一個數x,y^x,當y^x再次遇到x時就會把x抵消掉,按照這種操作,最後剩下的就是出現次數為1的數了
1 #include <cstdio> 2 #include <algorithm> 3 using namespace std; 4 5 int main(void) 6 { 7 int n; 8 while(~scanf("%d",&n) && n!=0) 9 { 10 int x,temp=0; 11 for(int i=1;i<=n;i++) 12 { 13 scanf("%d",&x); 14 temp=temp^x; 15 } 16 printf("%d\n",temp); 17 } 18 19 return 0; 20 }
方案二:
STL之map容器
關於map基本操作參考如下鏈接:
https://www.jianshu.com/p/0cd5cca5c4e0
map就像是python裏面的字典有一組鍵值對,key-value
key由const修飾,故key不可改變,此題中出現的數字可以作為key,次數作為value,形成對應關系
1 #include <map> 2 #include <cstdio> 3 #include <algorithm> 4 using namespace std; 5 6 int main(void) 7 { 8 int n,a; 9 10 while(~scanf("%d",&n) && n!=0) 11 { 12 map<int,int>m; 13 map<int,int>::iterator it; 14 for(int i=1;i<=n;i++) 15 { 16 scanf("%d",&a); 17 m[a]++; 18 } 19 20 for(it=m.begin();it!=m.end();it++) 21 { 22 if(it->second==1) 23 { 24 printf("%d\n",it->first); 25 break; 26 } 27 } 28 } 29 30 return 0; 31 }
據說,因為數據小,所以可以用位運算,否則也會超時,數據大時用map會更省時。但是針對本題,還是位運算省時;(‘;‘程序員般結尾23333)
hdu-2095 find your present(2)