Socializing can be a very complicated thing among teenagers. Forexample, finding a good seating arrangement in a movie theater can be adifficult task. Here is a list of constraints that could potentiallyapply to two individuals A and B in this situation:
Teenage politics is a complicated thing meaning the constraints canget even more complicated than those listed above.However, we restrict this problem to a particular form of constraintthat simply specifies a lower or upper bound on the number of seatsseparating two specific individuals.
The group arrives after everyone else watching the show has beenseated. By some stroke of luck, there are exactly as many open seats asthere are teenagers and all of these seats appear consecutively in thefront row. How many possible seating arrangements satisfy theconstraints?
Each test case begins with two integers n and m with 0 < n ≤ 8and 0 ≤ m ≤ 20where n is the size of the group. For simplicity, assume the teenagersare numbered from 0 to n-1. Then of m lines follow, each describing aconstraint, where a line consists of three integers a,b,c satisfying 0≤ a < b < n and 0 < |c| < n. If c is positive thenteenagers a and b must sit at most c seats apart. Ifc is negative, then a and b must sit at least -c seats apart. The endof input is signaled by a line consisting of n = m = 0.
The output for each test case is a single line containing the numberof possible seating arrangements for the group that satisfy all of thesocial constraints.
3 1 0 1 -2 3 0 0 0
2 6题意:给出n个数,0到n-1,然后给出m个约束条件,形式为a b c,如果 c>0,表示数字a与b的距离<=c,如果c<0,表示a与b 的距离>=c,求排列中满足这样条件的个数
思路:用DFS求出一个排开后,判断是否满足约束条件
#include <cstdio> #include <algorithm> #include <cstdlib> using namespace std; const int MAXN = 30; struct Node { int a, b, c; }; Node node[MAXN]; int n, m; int teenage[MAXN]; int pos[MAXN]; int ans; bool input() { scanf("%d%d", &n, &m); if (n == 0 && m == 0) return false; for (int i = 0; i < m; i++) { scanf("%d%d%d", &node[i].a, &node[i].b, &node[i].c); } return true; } void dfs(int cur) { if (cur >= n) { bool flag = true; for (int i = 0; i < m && flag; i++) { if (node[i].c > 0) if (abs(pos[node[i].a] - pos[node[i].b]) > node[i].c) flag = false; if (node[i].c < 0) if (abs(pos[node[i].a] - pos[node[i].b]) < -node[i].c) flag = false; } if (flag) ans++; return; } for (int i = cur; i < n; i++) { swap(teenage[cur], teenage[i]); pos[teenage[cur]] = cur; pos[teenage[i]] = i; dfs(cur + 1); swap(teenage[cur], teenage[i]); pos[teenage[cur]] = cur; pos[teenage[i]] = i; } } void solve() { for (int i = 0; i < n; i++) { teenage[i] = i; pos[i] = i; } ans = 0; dfs(0); printf("%d\n", ans); } int main() { #ifndef ONLINE_JUDGE freopen("d:\\OJ\\uva_in.txt", "r", stdin); #endif // ONLINE_JUDGE while (input()) { solve(); } return 0; }