好久沒寫編程題了,手生的厲害,記錄一下。
首先做的第二題,比較簡單,ac。
題目要求:
比較簡單,用結構體記錄前后數字區間,按照start排序,當start相同時,按照end排序。然后循環合並即可。
測試用例:

4 3 8 3 7 4 6 7 9 5 3 8 3 7 4 6 7 9 1000 1100 4 0 1 3 7 10 11 8 9
代碼:
#include <iostream> #include <algorithm> using namespace std; struct st{ long long a,b; }; bool cmp(st aa, st bb){ if(aa.a==bb.a) return aa.b<bb.b; else return aa.a<bb.a; } int main() { int n; while(cin >> n) { st arr[n]; for(int i=0;i<n;i++) { cin >> arr[i].a >> arr[i].b; } sort(arr,arr+n,cmp); // for(int i=0;i<n;i++) // { // cout << arr[i].a <<" " << arr[i].b << endl; // } // cout << endl; st tem; tem.a=arr[0].a; tem.b=arr[0].b; for(int i=0;i<n;i++) { if(arr[i].a<=tem.b) { if(tem.b<arr[i].b){ tem.b=arr[i].b; } } else{ cout << tem.a << " " << tem.b << endl; tem.a=arr[i].a; tem.b=arr[i].b; } } cout << tem.a << " " << tem.b << endl; } return 0; }
然后做的第一題,第一題比第二題簡單,不過需要注意格式空間等問題,因為選擇填空浪費了太多時間,沒有全過。
第二題是給定幾個字符串,找出所有重復的字符串的序號
輸入:
第一行為n,字符串個數
第二行為m,字符串中數字的個數
第三行為字符。
可以把一行數字當做字符串處理,然后判斷字符串是否相等。
測試用例:魔改版本,方便測試進行了一些修改,m值對不上

11 0 195 946 1 427 2 367 718 202 187 683 321 831 3 1023 78 310 816 158 500 518 705 553 470 4 205 190 306 492 166 49 791 961 5 665 211 1009 614 15 683 6 195 946 7 678 198 495 8 205 190 306 492 166 49 791 961 9 83 74 1023 453 692 10 195 946
。
#include <iostream> #include <string> #include <cstring> #include <algorithm> #include <cstdio> using namespace std; char arr[10000][10010]; int state[10010]; int main() { int n; while(cin >> n) { memset(state,0,sizeof(state)); int num; for(int i=0;i<n;i++) { cin >> num; char c; scanf("%c",&c); gets(arr[i]); } for(int i=0;i<n;i++) { if(state[i]!=0) continue; state[i]=1; int a=0; for(int j=i+1;j<n;j++) { if(state[j]!=0) continue; //cout << i << " " << j << " " << strcmp(arr[i],arr[j]) << endl; if(strcmp(arr[i],arr[j])==0) { state[j]=1; //cout << "state " << j << endl; if(a==0){ cout << i; a=1; } cout << " " << j; } } if(a==1) cout <<endl; a=0; } } return 0; }
用這個方法要注意輸入格式,不要有多余的空格。
記錄一個愚蠢的版本,把state[i]==0放到了for循環中,導致當i標記為0時,運行到此便停止,應該是跳過標記為0的點,簡直愚蠢。
#include <iostream> #include <string> #include <cstring> #include <algorithm> #include <cstdio> using namespace std; char arr[10000][10010]; int state[10010]; int main() { int n; while(cin >> n) { memset(state,0,sizeof(state)); int num; for(int i=0;i<n;i++) { cin >> num; char c; scanf("%c",&c); //cout << num << "num " << endl; gets(arr[i]); //cout << arr[i]; } for(int i=0;i<n&&state[i]==0;i++) { state[i]=1; int a=0; for(int j=i+1;j<n&&state[j]==0;j++) { //cout << i << " " << j << " " << strcmp(arr[i],arr[j]) << endl; if(strcmp(arr[i],arr[j])==0) { state[j]=1; //cout << "state " << j << endl; if(a==0){ cout << i; a=1; } cout << " " << j; } } if(a==1) cout <<endl; a=0; } } return 0; }
跟同學投的不是一個公司,自己做的,應該是涼了