快乐之城是一个非常愉快的城市,这个城市由n个片区组成,片区与片区之间由n-1条道路相连。任意两个片区之间,都存在一条简单路径可以到达。
现在有两个人,小红与小明,正在快乐之城中旅游。但是小红与小明的关系不是很好,所以他们都不想在旅行的过程中碰见对方。
而你作为他们旅行的规划师,需要制定出完美的计划,满足这两个人的旅行路径不相交的目标。
当然,这两个人的旅行路径都是从一个地方旅行到另外一个地方,且他们的路线一定是最短的路线。
请问,能够构造出多少种不同的计划呢?
快乐之城是一个非常愉快的城市,这个城市由n个片区组成,片区与片区之间由n-1条道路相连。任意两个片区之间,都存在一条简单路径可以到达。
现在有两个人,小红与小明,正在快乐之城中旅游。但是小红与小明的关系不是很好,所以他们都不想在旅行的过程中碰见对方。
而你作为他们旅行的规划师,需要制定出完美的计划,满足这两个人的旅行路径不相交的目标。
当然,这两个人的旅行路径都是从一个地方旅行到另外一个地方,且他们的路线一定是最短的路线。
请问,能够构造出多少种不同的计划呢?
第一行一个整数n,表示快乐之城由n条片区组成。
接下来n-1行,每行两个整数x,y,表示片区x与片区y相连。
输出一共有多少种计划
4 1 2 2 3 3 4
8
表示小明的旅行计划是从A走到B,小红的旅行计划是从C走到D。
<1,2,3,4>,<2,1,3,4>,<1,2,4,3>,<2,1,4,3>
<3,4,1,2>,<3,4,2,1>,<4,3,1,2>,<4,3,2,1>
就以上八种计划。
1≤n≤30000
1≤x,y≤n
题目是好题目,测试用例太蠢了
/** * 算法思路: * 首先找到最长的路径 * 记最长的路径长度为 2l * 则方案数量为((l!)^2)*2 */ #include #include #include #include using namespace std; class Solution { private: vector map; int out; public: Solution(/* args */); ~Solution(); void slove(); friend ostream& operator<<(ostream& os, const Solution& s); friend istream& operator>>(istream& is, Solution& s); }; Solution::Solution(/* args */) { } Solution::~Solution() { } void Solution::slove() { int length = this->map.size(); int max_length = 0; vector path(length, 0); // path[i] 表示以 i 开头的最长路径长度 for (size_t i = 1; i <= length; i++) { if (path[i] != 0) { // 已整理路径 continue; } if (map[i] == 0) { path[i] = 1; continue; } // 有下一个结点 stack s; int next = map[i]; while (path[next] == 0 && map[next] != 0) { /* 未计算出结点,并且未到达终点 */ s.push(next); next = map[next]; } if (path[next] == 0) { /* 到达终点 */ path[next] = 1; } int now_length = path[next] + 1; while (!s.empty()) { int pos = s.top(); s.pop(); path[pos] = now_length++; } path[i] = now_length; if (now_length > max_length) { max_length = now_length; } } max_length /= 2; if (max_length % 2 == 1) { // 奇数可以后移一个结点 out = 4; } else { out = 2; } for (size_t i = 2; i <= max_length; i++) { out *= (i * i); } } ostream& operator<<(ostream& os, const Solution& s) { os << s.out; return os; } istream& operator>>(istream& is, Solution& s) { size_t n; is >> n; s.map.resize(n + 1, 0); for (size_t i = 0; i < n - 1; i++) { int x, y; is >> x >> y; s.map[x] = y; } return is; } int main(int argc, char* argv[]) { Solution s; cin >> s; s.slove(); cout << s << endl; return 0; }
while True: try: n=int(input().strip()) r=[] sum1=0 for i in range(n-1): r.append(list(map(int,input().split(' ')))) for i in range(n-1): num=0 index=r[i] for j in range(n-1): if r[j][0] not in index and r[j][1] not in index: num+=1 sum1+=2*num sum1=2*sum1 print(sum1) except: break
n = int(input()) half = int(n / 2) tmp = 1 for i in range(2,half + 1): tmp *= i tmp *= 2 * 2 if n % 2 == 1: print(tmp * n) else: print(tmp)上面的题目好多描述不清啊。。。看了实例的讲解,就是地点分两批,a旅行前面一批,b旅行后面一批,旅行完后两人进行交换。。。加上又不限定每个地点又没有强制只能走一次,所以任一批进行排列就好了。。。也就是(A 0 n/2)* 2 * 2 (奇数情况还没怎么想通,因为多了一个,所以每一个都有可能被分出来,所以乘以一个n?)