【Gym - 101196F】Removal Game (环形区间dp,环状,细节优化)
題干:
健健開發了一個游戲叫做<<者護守形隱>>,里面有一個情節是這樣的,女主子純藤武被壞人關在了密室里,作為男主的肖健當然要英雄救美。但是要打開密室的門,必須解開一道謎題。
門上有幾個數字圍成的一個圈,每次消除一個數字的代價是這個數字旁邊的兩個數字的gcd,當最后消的只剩兩個數時,消除這兩個數的代價就是這兩個數字的gcd,密室的密碼就是消除所有數字的最小代價。
請你幫助肖健解決這個問題
例如數字2,3,4,5,他可以以2的代價(gcd(2,4)==2)消除3,或者以1的代價(gcd(3,5)==1)消除4,或者以1的代價(gcd(3,5)==1)消除2
Input
Input contains multiple test cases. Each test case consists of a single line starting with an integer?n?which indicates the number of values in the sequence (2 ≤ n ≤ 100). This is followed by?n?positive integers which make up the sequence of values in the game. All of these integers will be ≤ 1000. Input terminates with a line containing a single 0. There are at most 1000 test cases
Output
For each test case, display the minimum cost of removing all of the numbers
Sample Input 1
4 2 3 4 5
5 14 2 4 6 8
0
Sample Output 1
3
8
題目大意:
一個環狀數組,給定可以刪去一個數,代價的相鄰兩個數的gcd,求最小代價。
解題報告:
這題如果不提前把gcd打出來在codeforce上不會T(900ms左右),但是比賽的機子好像就T了。但是這題其實是可以變成環來做的。但是區別就是最后的更新ans不能直接就是讓他長度是n的來更新,因為最后剩下的兩個點可能在任意的位置,所以我們需要n^2枚舉這兩個位置,然后分別更新答案,這樣得到的才是正解。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define F first #define S second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e5 + 5; int a[MAX]; int g[1005][1005]; int dp[205][205]; int n; int main() {for(int i = 0; i<=1000; i++) {for(int j = 0; j<=1000; j++) {g[i][j] = __gcd(i,j);}}while(~scanf("%d",&n)) {if(n == 0) break;memset(dp,0x3f,sizeof dp);for(int i = 1; i<=n; i++) scanf("%d",a+i),a[i+n] = a[i];for(int i = 1; i<=2*n - 1; i++) dp[i][i+1] = 0;//g[a[i]][a[i+1]];for(int i = 1; i<=2*n; i++) dp[i][i] = 0;for(int len = 3; len<=n; len++) {for(int l = 1; l+len-1<=2*n; l++) {int r = l+len-1;for(int k = l+1; k<r; k++) {dp[l][r] = min(dp[l][r] , dp[l][k] + dp[k][r] + g[a[l]][a[r]]);}}}int ans = 0x3f3f3f3f;for(int i = 1; i<=n; i++) {for(int j = i+1; j<=n; j++) {ans = min(ans,dp[i][j] + dp[j][i+n] + g[a[i]][a[j]]);}}printf("%d\n",ans);}return 0 ; }?
總結
以上是生活随笔為你收集整理的【Gym - 101196F】Removal Game (环形区间dp,环状,细节优化)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 曝NVIDIA新卡GTX 1630下周发
- 下一篇: 【HDU - 4055】Number S