Codeforces 11.27 B

B. Restoring IPv6

状态不好,看来好久才看出题意,字符处理始终是我的弱项,有空联系下。记录一下。

View Code
 1 #include <iostream>
 2 #include <cassert>
 3 #include <cstdio>
 4 #include <cstring>
 5 #include <vector>
 6 #include <algorithm>
 7 using namespace std;
 8 
 9 const int MM = 110010;
10 #define fuck puts("fuck")
11 #define VI vector<int>
12 typedef long long int64;
13 #define mod 1000000007
14 
15 char ch[MM];
16 
17 void solve() {
18     int i,j,k,len;
19     scanf("%s",ch);
20     len=strlen(ch);
21     if(len==2&&ch[0]==':'&&ch[1]==':') {
22         for(i=0;i<7;i++) printf("0000:"); puts("0000");
23     }
24     else {
25         int pos[MM]={0},all=0;
26         for(i=0;ch[i];i++) if(ch[i]==':') all++;
27         if(ch[len-1]==':'&&ch[len-2]==':') pos[len-2]=1;
28         for(i=0;i<len-2;i++) {
29             if(ch[i]==':'&&ch[i+1]==':') {
30                 if(ch[i-1]=='0'&&ch[i+2]=='0') pos[i]=2;
31                 else pos[i]=3;
32             }
33         }
34 //        for(i=0;i<len;i++) printf("%d %d\n",i,pos[i]);
35         int zero=9-all;
36         for(i=0;i<len;i++) {
37             for(j=i;j<=i+4;j++) if(ch[j]==':'||j==(len)) break;
38             for(k=0;k<(-j+i+4);k++) printf("0");
39             for(k=i;k<j;k++) printf("%c",ch[k]);
40             if(ch[j]==':') {
41             if(pos[j]==0)  printf(":"),i=j;
42             else if(pos[j]==1) {
43                for(k=0;k<zero;k++)printf(":0000");i=j+1;
44             }
45 //            else if(pos[j]==2) printf(":0000:"),i=j+1;
46             else {
47                 for(i=1;i<zero;i++) printf(":0000");
48                 printf(":");
49                 i=j+1;
50             }
51             }
52             else i=j+1;
53         }
54         puts("");
55     }
56 }
57 
58 int main() {
59     int ca; scanf("%d",&ca);
60     while(ca--) solve();
61     return 0;
62 }
原文地址:https://www.cnblogs.com/zhang1107/p/2791533.html