Codeforces 387C George and Number(貪心)
阿新 • • 發佈:2018-12-23
題目大意:給定一個數,要求找到一個集合,通過題目給定的變換方式可以得到給定得數,輸出集合元素個數的最大值。變換方式為每次從集合中取出任意兩個數,連線成一個新的數,要求兩個數中較大的數必須放在前面;然後連線成的新的數放回集合中,重複上述操作,直到只剩一個數。(元素不可以是0)
解題思路:揣摩題意揣了很久。貪心,以為要集合元素儘量多,所以元素的值就要儘量小,這樣的話就可以讓每個數都做為一個元素,然後保證第一個比第二個大即可,像滾雪球一樣一直和下一個元素相連線,變大。但是因為題目有一個要求,就是說元素不可以為0,所以所有的0都要歸結到前面第一個非0元素,這樣就導致在滾雪球的時候碰到一個比自己大的雪球,即當前位置的0非常多,記得重新計數。
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; const int N = 100005; int n, v[N], c[N]; char num[N]; void init () { n = 0; memset(v, 0, sizeof(v)); memset(c, 0, sizeof(c)); scanf("%s", num); int x = 0; for (int i = strlen(num) - 1; i >= 0; i--) { x++; if (num[i] != '0') { c[n] = x; v[n] = num[i] - '0'; n++; x = 0; } } } int solve () { int ans = 1; int cnt = c[n-1], val = v[n-1]; for (int i = n-2; i >= 0; i--) { if (cnt > c[i] || (cnt == c[i] && val >= v[i])) ans++; else ans = 1; cnt += c[i]; } return ans; } int main () { init(); printf("%d\n", solve()); return 0; }