我重写行不?

 

Comma Sprinkler

签到题,类似于BFS用两个队列维护每种单词前/后是否有逗号向前/后扩展,需要注意如果有句号挡着是不能扩展过去的,不过样例有。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int maxn = 1e6 + 10;
 4 map<string, vector<int>> M;
 5 bool pre[maxn], suc[maxn];
 6 bool st[maxn], ed[maxn];
 7 queue<string> QP, QS;
 8 set<string> SP, SS;
 9 string str[maxn];
10 
11 int main() {
12     string s;
13     getline(cin, s);
14     int l = s.length(), p = 1;
15     st[p] = true;
16     for(int i = 0; i < l; ++i) {
17         if(s[i] == ',') {
18             suc[p] = pre[p + 1] = true;
19             ++p, ++i;
20         }
21         else if(s[i] == '.') {
22             ed[p] = st[p + 1] = true;
23             ++p, ++i;
24         }
25         else if(s[i] == ' ') ++p;
26         else str[p].push_back(s[i]);
27     }
28     for(int i = 1; i < p; ++i) M[str[i]].push_back(i);
29     for(int i = 1; i < p; ++i) {
30         if(pre[i] && SP.find(str[i]) == SP.end()) SP.insert(str[i]), QP.push(str[i]);
31         if(suc[i] && SS.find(str[i]) == SS.end()) SS.insert(str[i]), QS.push(str[i]);
32     }
33     while(!QP.empty() || !QS.empty()) {
34         while(!QP.empty()) {
35             string cur = QP.front(); QP.pop();
36             vector<int>& pos = M[cur];
37             for(int i = 0; i < pos.size(); ++i) {
38                 int x = pos[i];
39                 if(!st[x]) pre[x] = true;
40                 if(x - 1 > 0 && !ed[x - 1] && SS.find(str[x - 1]) == SS.end()) suc[x - 1] = true, SS.insert(str[x - 1]), QS.push(str[x - 1]);
41             }
42         }
43         while(!QS.empty()) {
44             string cur = QS.front(); QS.pop();
45             vector<int>& pos = M[cur];
46             for(int i = 0; i < pos.size(); ++i) {
47                 int x = pos[i];
48                 if(!ed[x]) suc[x] = true;
49                 if(x + 1 < p && !st[x + 1] && SP.find(str[x + 1]) == SP.end()) pre[x + 1] = true, SP.insert(str[x + 1]), QP.push(str[x + 1]);
50             }
51         }
52     }
53     for(int i = 1; i < p; ++i) {
54         cout << str[i];
55         if(ed[i]) cout << '.';
56         else if(suc[i]) cout << ',';
57         if(i < p - 1) cout << ' ';
58         else cout << endl;
59     }
60     return 0;
61 }
Aguin

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-14
猜你喜欢
  • 2021-04-10
  • 2021-07-07
  • 2021-09-16
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案