CodeForces - 1325D Ehab the Xorcist(构造+异或)
題目鏈接:點(diǎn)擊查看
題目大意:給出一個(gè) u 和一個(gè) v ,要求構(gòu)造出最短的一個(gè)數(shù)組,使得
輸出構(gòu)造的結(jié)果
題目分析:情況稍微比較復(fù)雜的一道構(gòu)造題,讀完題后,先根據(jù)樣例特判,當(dāng) u 和 v 為 0 時(shí),答案為 0 ,當(dāng) u 和 v 相等時(shí),答案為 u,當(dāng) u > v 時(shí),答案為 -1,這些根據(jù)樣例的提示應(yīng)該不難想
接下來我們應(yīng)該構(gòu)造通項(xiàng),根據(jù)異或的性質(zhì), u xor u = 0,加上經(jīng)過上面的篩選之后,我們可以構(gòu)造一個(gè)長(zhǎng)度為 3 的數(shù)組,其值分別為 x y y ,令 x = u ,顯然滿足 x ^ y ^ y = u ,現(xiàn)在只需要滿足 u + y + y = v 就好了,解方程得到 y = ( v - u ) / 2 ,所以這里必須滿足 v - u 可以被 2 整除才行,如果不能被整除那么答案就是 -1 了,到此為止所有的特判都已經(jīng)完成了,但是根據(jù)樣例的提示,我們發(fā)現(xiàn)答案會(huì)有長(zhǎng)度為 2 的數(shù)組,這個(gè)該怎么辦呢,其實(shí)經(jīng)過上面的分析,我們可以發(fā)現(xiàn),長(zhǎng)度為 2 的數(shù)組其實(shí)就是 x y y 合并成了 x + y , y 了而已,這也就啟發(fā)了我們的思路,我們接下來的問題就轉(zhuǎn)換為了分析出什么時(shí)候可以將 x y y 合并成 x + y? y ,因?yàn)榧臃ㄟ\(yùn)算滿足結(jié)合律,x + y + y 和 ( x + y ) + y 是等價(jià)的,所以我們只需要考慮什么時(shí)候 x ^ y ^ y = ( x + y ) ^ y ,同時(shí)約分掉 y 后,可以得到當(dāng) x ^ y = x + y 時(shí)滿足三項(xiàng)可以合并為兩項(xiàng),到這里應(yīng)該不難猜出,當(dāng)且僅當(dāng) x & y == 0 時(shí),三項(xiàng)可以合并為兩項(xiàng)了
代碼:
#include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=1e4+100;int main() { #ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); #endif // ios::sync_with_stdio(false);LL u,v,w;scanf("%lld%lld",&u,&v);if(u>v||(u-v)%2)return 0*printf("-1\n");if(u==0&&v==0)return 0*printf("0\n");if(u==v)return 0*printf("1\n%lld\n",v);w=(v-u)/2;if((u&w)==0)return 0*printf("2\n%lld %lld\n",w,w+u);printf("3\n%lld %lld %lld\n",u,w,w);return 0; }?
總結(jié)
以上是生活随笔為你收集整理的CodeForces - 1325D Ehab the Xorcist(构造+异或)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDU - 1890 Robotic S
- 下一篇: CodeForces - 1326E B