【noip模拟赛4】Matrix67的派对 暴力dfs
生活随笔
收集整理的這篇文章主要介紹了
【noip模拟赛4】Matrix67的派对 暴力dfs
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【noip模擬賽4】Matrix67的派對
做法:
用dfs試每一條路,記錄一個步數step,當step==n,切該點和起點差距小于k時,答案就累計一個。
開3個數組:
1 pre 記錄 step-1 時,是哪個點,用來與step時的各個數比較判斷能否做一起。
2 flag 在試沒一條路時,用flag標記每一條路,防止死循環,這條路探完后,重置為0。
3 high 記錄每個人的高。
注意:有特解 當n=1時,ans 應為1。 #include<iostream> #include<cmath> #include<stdio.h> #include<vector> #include<string.h> #include<math.h> #include<algorithm> using namespace std; const int maxn=11; int high[maxn],pre[maxn]; int n,k,ans; bool flag[maxn];void dfs(int step) {for(int i=2;i<=n;i++){if(!flag[i]&&abs(high[i]-high[pre[step-1]])<=k){flag[i]=1;pre[step]=i;if(step==n&&abs(high[pre[step]]-high[1])<=k){ans++;}elsedfs(step+1);flag[i]=0;}} }int main(void) {// freopen("input.txt","r",stdin);cin>>n>>k;for(int i=1;i<=n;i++){cin>>high[i];}if(n==1)ans=1;else{ans=0;flag[1]=1;pre[1]=1;dfs(2);}cout<<ans<<endl;return 0; }
描述
?
Matrix67發現身高接近的人似乎更合得來。Matrix67舉辦的派對共有N(1<=N<=10)個人參加,Matrix67需要把他們安排在圓桌上。Matrix67的安排原則是,圓桌上任意兩個相鄰人的身高之差不能超過K。請告訴Matrix67他共有多少種安排方法。
?
輸入
?
第一行輸入兩個用空格隔開的數N和K,其中1<=N<=10,1<=K<=1 000 000。
第二行到第N+1行每行輸入一個人的身高值。所有人的身高都是不超過1 000 000的正整數
?
輸出
?
輸出符合要求的安排總數
?
輸入樣例 1?
4 10 2 16 6 10輸出樣例 1
2做法:
用dfs試每一條路,記錄一個步數step,當step==n,切該點和起點差距小于k時,答案就累計一個。
開3個數組:
1 pre 記錄 step-1 時,是哪個點,用來與step時的各個數比較判斷能否做一起。
2 flag 在試沒一條路時,用flag標記每一條路,防止死循環,這條路探完后,重置為0。
3 high 記錄每個人的高。
注意:有特解 當n=1時,ans 應為1。 #include<iostream> #include<cmath> #include<stdio.h> #include<vector> #include<string.h> #include<math.h> #include<algorithm> using namespace std; const int maxn=11; int high[maxn],pre[maxn]; int n,k,ans; bool flag[maxn];void dfs(int step) {for(int i=2;i<=n;i++){if(!flag[i]&&abs(high[i]-high[pre[step-1]])<=k){flag[i]=1;pre[step]=i;if(step==n&&abs(high[pre[step]]-high[1])<=k){ans++;}elsedfs(step+1);flag[i]=0;}} }int main(void) {// freopen("input.txt","r",stdin);cin>>n>>k;for(int i=1;i<=n;i++){cin>>high[i];}if(n==1)ans=1;else{ans=0;flag[1]=1;pre[1]=1;dfs(2);}cout<<ans<<endl;return 0; }
?
轉載于:https://www.cnblogs.com/zgncbsylm/p/10579988.html
總結
以上是生活随笔為你收集整理的【noip模拟赛4】Matrix67的派对 暴力dfs的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于javascript遍历对象
- 下一篇: ABAP WRITE