中石油训练赛 - Edit Distance(思维+构造)
題目描述
A binary string is a non-empty sequence of 0’s and 1’s, e.g., 010110, 1, 11101, etc. The edit distance of two binary strings S and T, denoted by edit(S,T), is the minimum number of single-character edit (insert, delete,or substitute) to modify S into T. For example, the edit distance of 0011 and 1100 is 4, i.e. 0011->011 ->11->110->1100. The edit distance of 1100101 and 1110100 is 2, i.e. 1100101->1110101->1110100.
Ayu has a binary string S. She wants to find a binary string with the same length as S that maximizes the edit distance with S. Formally, she wants to find a binary string Tmax such that |S| = |Tmax| and edit(S,Tmax)≥edit(S,T') for all binary string T' satisfying |S| = |T'|.
She needs your help-> However, since she wants to make your task easier, you are allowed to return any binary string T with the same length as S such that the edit distance of S and T is more than half the length of S. Formally, you must return a binary string T such that |S| = |T| and edit(S,T) > |S|/2 .
Of course, you can still return Tmax?if you want, since it can be proven that edit(S,Tmax) > |S|/2 for any binary string S. This also proves that there exists a solution for any binary string S. If there is more than one valid solution, you can output any of them.
?
輸入
Input contains a binary string S (1≤|S|≤2000).
?
輸出
Output in a line a binary string T with the same length as S that satisfies edit(S,T) > |S|/2.
樣例輸入
0011樣例輸出
1100題目大意:給出一個由0和1組成的字符串,給定edit的定義,設給定字符串長度為len,求一個長度為len,edit大于len/2的字符串
題目分析:首先需要明確edit的定義,edit(S,T)的意思是通過刪除、增加、替換這三種操作,將S字符串變為T字符串所需要的最小操作次數,因為題目只需要輸出滿足edit大于len/2即可,所以成了一個比較水的題目了,我們可以構造特殊情況來滿足所有的一般情況,一開始我們是分奇偶來討論的,結果發現奇偶討論的話還是建立在給定字符串的0和1數目是否相等的基礎上,如果0和1的數目不相等,我們可以直接把字符串變為全是0或全是1,這樣操作次數必定大于len/2,如果0的數目等于1的數目,則只需要根據第一位取異或,其余位置取第一位的異或即可,即,若給定字符串為1100,我們輸出0111,給定字符串為0011,我們輸出1000,雖然不太會證明為什么可以這樣做,但是我們沒發現反例。。最后官方給出的題解也是這樣寫的,還是有點小成就感的,上代碼:
#include<iostream> #include<string> using namespace std;int main() {string str;while(cin>>str){int cnt1=0;int cnt0=0;for(int i=0;i<str.size();i++){if(str[i]=='1')cnt1++;elsecnt0++;}if(cnt1>cnt0){for(int i=0;i<str.size();i++)printf("%d",0);}else if(cnt0>cnt1){for(int i=0;i<str.size();i++)printf("%d",1);}else{int flag;flag=str[0]=='1';for(int i=0;i<str.size();i++){if(i)printf("%d",flag);elseprintf("%d",!flag);}}cout<<endl;}return 0; }?
總結
以上是生活随笔為你收集整理的中石油训练赛 - Edit Distance(思维+构造)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: POJ - 2104 K-th Numb
- 下一篇: 中石油训练赛 - Isomorphic