0

## 算法题，编程语言不限，c，java，py

newkevin iT邦高手 1 級 ‧ 2021-03-19 08:00:40 檢舉

### 1 個回答

2

iT邦大神 1 級 ‧ 2021-03-17 17:06:48
``````#include <iostream>
#include <cstring>

using namespace std;
long long ans, cnt1, cnt2, V, n;
char s[100010];

int main()
{

cin >> V >> s;
n = strlen(s);

for(int i= 0; i < n; i++)
{
if(s[i] == '2'){
if(cnt1 + 2 * cnt2 + 2 <= V) cnt2++;
}else
{
//s[i] = 1;
if(cnt1 + 2 * cnt2 + 1 <= V) cnt1++;
else if(cnt2>0) cnt2 --, cnt1++;
}
ans += cnt2+cnt1;
}

cout << ans << endl;

return 0;
}
``````

C++資料來源

``````public static void main(String[] args) {
int num =1 ;
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
String s = scanner.nextLine();

int dayNum = 0;
int totalNum = 0;
int[] a = new int[s.length()];
int number = 0;//背包现有药材占的份额
for(int i = 1 ;i < s.length();i++) {
int value = s.charAt(i) -48;
int c = number + value;
if (c <= n) {
number += value;
a[i] = value;
dayNum++;
totalNum += dayNum;
}
if (c > n && value == 1) {
boolean flag = true;
for (int j = 0; j < a.length; j++) {
if (a[j] == 2) {
a[j] = 1;
number = number-1;
flag = false;
totalNum += dayNum;
break;
}
}
if(flag)
totalNum += dayNum;
}
if(value == 2 &&c > n){
totalNum += dayNum;
}

}
System.out.println(totalNum);
}
``````

java 資料來源