//vs2013下編譯通過.換別的編譯器自行補充頭文件和修改源代碼
#include<iostream> #include<fstream> #include <string> using namespace std; char temp[256];//存放的臨時數組 char virus[20];//病毒數組 char DNA[20];//DNA的數組 int j = 0;//病毒長度 int DNAlength = 0;//dna長度 int flag = 0;//判斷是不是感染開關 void toCharArry(string str)//將讀入的字符串轉化為字符數組 { j = 0; int tem=0; strcpy_s(temp, str.c_str()); //cout << str.length(); for (int i = 0; i < str.length(); i++)//找到空格的位置 { if (temp[i] == ' '){ j=(i+1); break; } } tem = j; for (int i = 0; i < str.length() - j + 1;i++)//寫入DNA數組; { DNA[i] = temp[tem]; if (i == str.length() - j){ DNA[i] = '\0';//到底用不用加\我也不知道 } tem++; } for (int i = 0; i < j; i++)//得到病毒序列 { virus[i] = temp[i]; } /*for (int i = 0; i <9; i++)//輸出Dna序列 { cout <<DNA[i]; } cout << endl; for (int i = 0; i < j; i++)//輸出病毒序列 { cout << virus[i]; } cout << endl; cout << j;*/ } void addvVirusToDouble(char virus[])//將病毒序列擴大為原來二倍 { int k = j-1; for (int i = 0; i < j-1 ; i++) { virus[k] = virus[i]; k++; } /*for (int i = 0; i < j*2; i++)//輸出病毒序列 { cout << virus[i]; } cout << endl;*/ } int BF(int zhu, int fu, char virus[], char DNA[])//BF算法判斷 { int i = 0, j = 0; while (i <= zhu&&j <= fu) { if (DNA[i]==virus[j]){ i++; j++; } else { i = i - j + 1; j = 0; } } if (j > fu){ return 1; } else return 0; } void virusPossibility()//列出將長度擴大二倍的病毒序列可能性 { char temp[30]; for (int i = 0; i < j; i++) { for (int k = 0; k < j; k++)temp[k] = virus[i + k]; //temp[j] = '\0'; if (BF(DNAlength - j - 1, j - 2, temp, DNA) == 1)flag = 1; } /*if (flag == 1) { flag = 0; cout << "O" << endl; } else cout << "X" << endl; */ } void detection()//調用函數判斷是否感染 { int num = 0; string str; ifstream infile("病毒檢測輸入數據.txt", ios::in); ofstream outfile("病毒檢測結果.txt", ios::out); if (!infile){ cout << "open document ERROE!!" << endl; exit(-1); } else cout << "The document reads into success!!" << endl; if (!outfile){ cout << "Establish document failure ERROE!!" << endl; exit(-1); } getline(infile, str); num = stof(str);//賦值給num之后判斷; //cout << num; while (num--) { getline(infile, str); DNAlength = str.length(); toCharArry(str); addvVirusToDouble(virus); virusPossibility(); if (flag == 1){ flag = 0; outfile << str + " " + "YES" << endl; }//媽的這里必須把flag弄成0,要不只要有一個是下面的都是了... else { outfile << str + " " + "NO" << endl; } } infile.close(); outfile.close(); } int main() { string str; detection(); cout << "The TXTdocument outputs success!!!" << endl; }
程序截圖:
老師讓思考的作業,網上找了找也沒有找到,作為小白,自己動手寫了一下分享給大家,造福后來人,代碼寫的不夠好......不要亂噴謝謝!!