NC221007. Anotheramazingballon
描述
输入描述
One line,a string containing only letters u and d.(0 < the string's length <64)
输出描述
Output one line,one number about the answer.
示例1
输入:
udud
输出:
0
示例2
输入:
uddu
输出:
-1
Java(javac 1.8) 解法, 执行用时: 26ms, 内存消耗: 12008K, 提交时间: 2021-04-20 14:39:01
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); char[] abs = s.toCharArray(); long high = 0,c = 1; for(int i=0;i<abs.length;i++){ if(i>=1) { if (abs[i]==abs[i - 1]) c *= 2; else c = 1; } if(abs[i]=='u') high += c; else high -= c; } System.out.println(high); } }
C 解法, 执行用时: 2ms, 内存消耗: 392K, 提交时间: 2021-05-28 16:56:47
#include<stdio.h> #include<stdlib.h> int main(){ char a[64]; gets(a); long x=1; long sum=0; if(a[0]=='u') sum=1; if(a[0]=='d') sum=-1; for(int i=1;i<64;i++){ if(a[i]=='u'&&a[i-1]=='u'){ x=x*2; sum=sum+x; } if(a[i]=='u'&&a[i-1]=='d'){ x=1; sum=sum+x; } if(a[i]=='d'&&a[i-1]=='d'){ x=x*2; sum=sum-x; } if(a[i]=='d'&&a[i-1]=='u'){ x=1; sum=sum-x; } } printf("%lld",sum); }
Python3(3.9) 解法, 执行用时: 17ms, 内存消耗: 2816K, 提交时间: 2021-05-11 19:15:14
n = input() s = 0 s1 = 1 if n[0] == "u": s += 1 else: s -= 1 for i in range(1,len(n)): if n[i] == n[i-1] == "u": s1 *= 2 s += s1 elif n[i] == n[i-1] =="d": s1 *= 2 s -= s1 if n[i] != n[i-1]: s1 = 1 if n[i] == "u": s += 1 else: s -= 1 print(s)
C++(clang++11) 解法, 执行用时: 11ms, 内存消耗: 412K, 提交时间: 2021-04-23 12:43:03
#include<iostream> #include<algorithm> #include<cstring> using namespace std; int main() { string s; cin>>s; long long int h=1,sum=0; for(int i=0;i<s.size();i++) { if(i==0||s[i]!=s[i-1]) h=1; else if(s[i]==s[i-1]) h*=2; if(s[i]=='u') { sum+=h; } else if(s[i]=='d') { sum-=h; } } printf("%lld",sum); return 0; }