【codeforces 701C】They Are Everywhere

小鱼儿 2021-10-01 07:08 273阅读 0赞

【题目链接】:http://codeforces.com/contest/701/problem/C

【题意】

让你选择一段最短的区间;
使得这段区间里面包含所有种类的字符;

【题解】

之前都是用二分写;
现在会用类似队列的思路写了;
就是先确定左端点;
然后右端点右移;
直到出现所有种类;(这时候右端点就没必要再右移了)
然后右端点不动,右移左端点;
然后如果这时候又没有全部种类,就再右移右端点;
O(N)的复杂度吧

【Number Of WA】

0

【完整代码】

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define lson l,m,rt<<1
  4. #define rson m+1,r,rt<<1|1
  5. #define LL long long
  6. #define rep1(i,a,b) for (int i = a;i <= b;i++)
  7. #define rep2(i,a,b) for (int i = a;i >= b;i--)
  8. #define mp make_pair
  9. #define ps push_back
  10. #define fi first
  11. #define se second
  12. #define rei(x) cin >> x
  13. #define pri(x) cout << x
  14. #define ms(x,y) memset(x,y,sizeof x)
  15. typedef pair<int,int> pii;
  16. typedef pair<LL,LL> pll;
  17. const int dx[9] = {
  18. 0,1,-1,0,0,-1,-1,1,1};
  19. const int dy[9] = {
  20. 0,0,0,-1,1,-1,1,-1,1};
  21. const double pi = acos(-1.0);
  22. const int N = 1e5+100;
  23. map <char,int> dic;
  24. int n,tot,ans=N;
  25. char s[N];
  26. int main()
  27. {
  28. //freopen("F:\\rush.txt","r",stdin);
  29. ios::sync_with_stdio(false);
  30. rei(n);
  31. rei((s+1));
  32. rep1(i,1,n)
  33. if (!dic[s[i]])
  34. {
  35. dic[s[i]] = 1;
  36. tot++;
  37. }
  38. dic.clear();
  39. int l = 1,r = 1,now = 0;
  40. dic[s[1]] = 1;
  41. now = 1;
  42. while (r<=n)
  43. {
  44. if (l<=r && now==tot)
  45. {
  46. ans = min(ans,r-l+1);
  47. dic[s[l]]--;
  48. if (dic[s[l]]==0) now--;
  49. l++;
  50. }
  51. else
  52. {
  53. r++;
  54. if (r<=n)
  55. {
  56. dic[s[r]]++;
  57. if (dic[s[r]]==1) now++;
  58. }
  59. }
  60. }
  61. pri(ans<<endl);
  62. //printf("\n%.2lf sec \n", (double)clock() / CLOCKS_PER_SEC);
  63. return 0;
  64. }

转载于:https://www.cnblogs.com/AWCXV/p/7626437.html

发表评论

表情:
评论列表 (有 0 条评论,273人围观)

还没有评论,来说两句吧...

相关阅读