題目描述
We have a knapsack of integral capacity and some objects of assorted integral sizes. We attempt to fill the knapsack up, but unfortunately, we are really bad at it, so we end up wasting a lot of space that can’t be further filled by any of the remaining objects. In fact, we are optimally bad at this!
How bad can we possibly be?
figure out the least capacity we can use where we cannot place any of the remaining objects in the knapsack. For example, suppose we have 3 objects with weights 3, 5 and 3, and our knapsack has capacity 6. If we foolishly pack the object with weight 5 first, we cannot place either of the other two objects in the knapsack. That’s the worst we can do, so 5 is the answer.
How bad can we possibly be?
figure out the least capacity we can use where we cannot place any of the remaining objects in the knapsack. For example, suppose we have 3 objects with weights 3, 5 and 3, and our knapsack has capacity 6. If we foolishly pack the object with weight 5 first, we cannot place either of the other two objects in the knapsack. That’s the worst we can do, so 5 is the answer.
輸入
The first line of input contains two integers n (1 ≤ n ≤ 1,000) and c (1 ≤ c ≤ 105 ), where n is the number of objects we want to pack and c is the capacity of the knapsack.
Each of the next n lines contains a single integer w (1 ≤ w ≤ c). These are the weights of the objects.
Each of the next n lines contains a single integer w (1 ≤ w ≤ c). These are the weights of the objects.
輸出
Output a single integer, which is the least capacity we can use where we cannot place any of the remaining objects in the knapsack.
樣例輸入 Copy
3 6
3
5
3
樣例輸出 Copy
5
這個題只有1-9九個數字,我們可以求一個9的全排列,但是我們需要check一個排列行不行
一種容易想到的方法就是O(n)掃邊字符串就可以了
但是這樣復雜度並不能通過
這里繼續考慮這九種數字
每次移動都是在九種數字的任意兩種之間
那么我們處理出相鄰的兩數字出現的次數
然后check的時候只需要考慮對於一個排列枚舉兩種數字,然后算出距離×出現次數的和就可以了

int a[10],ans = inf,p[maxn],pos[10]; int len,num[66][66] ; char s[maxn]; int cal() { int temp=0; for(int i=1 ; i<=9 ; i++) pos[a[i]] = i; for(int i=1 ; i<=9 ; i++) for(int j=1 ; j<=9 ; j++) temp+=abs(pos[i]-pos[j])*num[i][j]; return temp+len+abs(pos[p[1]] - pos[a[1]] ); } int main() { scanf("%s",s+1); len = strlen(s+1); rep(i,1,len ) p[i] = s[i]-'0'; for(int i=1 ; i<len ; i++)num[p[i]][p[i+1]]++; rep(i,1,9) a[i] = i; do { ans = min(ans,cal()); } while(next_permutation(a+1,a+1+9)); out(ans); return 0; }