[USACO2015February,Bronze] Problem2.COW

来源:互联网 发布:php 汉字转ascii 编辑:程序博客网 时间:2024/06/03 12:51

Bessie the cow has stumbled across an intriguing inscription carved into a large stone in the middle of her favorite grazing field. The text of the inscription appears to be from a cryptic ancient language involving an alphabet with only the three characters C, O, and W. Although Bessie cannot decipher the text, she does appreciate the fact that C, O, and W in sequence forms her favorite word, and she wonders how many times COW appears in the text.

Bessie doesn’t mind if there are other characters interspersed within COW, only that the characters appear in the correct order. She also doesn’t mind if different occurrences of COW share some letters. For instance, COW appears once in CWOW, twice in CCOW, and eight times in CCOOWW.

Given the text of the inscription, please help Bessie count how many times COW appears.

INPUT FORMAT: (file cow.in)

The first line of input consists of a single integer N <= 10^5. The second line contains of a string of N characters, where each character is either a C, O, or W.

OUTPUT FORMAT: (file cow.out)

Output the number of times COW appears as a subsequence, not necessarily contiguous, of the input string.

Note that the answer can be very large, so make sure to use 64 bit integers (“long long” in C++, “long” in Java) to do your calculations.

SAMPLE INPUT:

6COOWWW

SAMPLE OUTPUT:

6

[Problem credits: Ben Cousins and Brian Dean, 2015]

数据范围是105,三层for循环肯定超时.
让我们考虑一下线性的算法,显然对我们来说重要的序列只有”C”,”CO”和”COW”,通过简单的分析我们可以发现:

  1. 如果当前的字符是’W’,那么”COW”出现的次数应该加上前面”CO”出现的次数;
  2. 如果当前的字符是’O’,那么”CO”出现的次数应该加上前面”C”出现的次数;
  3. 如果当前的字符是’C’,那么”C”出现的次数应该加1.

执行完这个过程,我们就能很容易得出”COW”出现的次数.

代码如下:

#include<cstdio>#include<iostream>#include<string>using namespace std;typedef long long LL;int n;LL C = 0, O = 0, W = 0;string S;int main(){  freopen("cow.in", "r", stdin);  freopen("cow.out", "w", stdout);  cin >> n >> S;  for(int i = 0; i < n; i++)  {    if(S[i] == 'C')      C++;    else if(S[i] == 'O')      O += C;    else if(S[i] == 'W')      W += O;  }  cout << W << endl;  return 0;}
0 0
原创粉丝点击