优化代码#include<iostream> #include<vector> #include<cstring> #include<algorithm> using namespace std; const int N = 1e6; vector<pair<int, int>>p; int n, Q; bool b[N]; int brr[N]; int arr[N]; int comt = 0; vector<int>a; int agg[N]; bool check(int a, int b) { for (int i = 0; i < p.size(); i++) { if (a == p[i].first && b == p[i].second) { return false; } } return true; } void dfs(int x){ if (x == n){ for (auto t : a)cout << t << " "; cout << "\n"; return; } for (int i = n; i >= 1; i--){ if (b[i] != true && check(x + 1, i)){ a.push_back(i); b[i] = true; dfs(x + 1); a.pop_back(); b[i] = false; } } return; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> Q; for (int i = 1; i <= Q; i++) { int x, y; cin >> x >> y; p.push_back({ x,y }); agg[y] = x; } dfs(0); return 0; }
时间: 2023-06-18 20:06:19 浏览: 106
这段代码主要是用来生成一个长度为n、不含给定对(x,y)的排列。
代码中的check函数是用来检查当前排列中是否含有给定的对(x,y),如果有则返回false。
在dfs函数中,我们从后往前枚举可能的数值,如果该数值没有被使用过且不含给定对,则将其加入当前排列中,继续递归生成下一个数,最后回溯恢复状态。
优化方面,可以考虑使用bitset来代替bool数组,这样可以减少内存空间的使用。同时,在check函数中可以使用unordered_set来代替vector,这样可以更快地判断当前排列是否含有给定对。最后,可以考虑使用迭代加深搜索(IDA*)来代替dfs,这样可以减少空间使用,提高效率。
相关问题
仅使用<iostream> #include <string> #include <cstdlib> #include <cstring> #include <cctype> #include <cmath> #include <cstdio> #include <cerrno> #include <clocale> #include <ctime> #include <cwchar> #include <cwctype> #include <iomanip> #include <numeric> #include <algorithm> #include <unistd.h> #include <sys/wait.h> #include <conio.h>库实现控制台填表式输入
### 控制台表格输入的实现方法
为了在控制台上实现类似于“填表”的功能,可以利用C++的标准库来处理用户的逐行输入并将其存储在一个二维数据结构中。这里推荐使用 `std::vector<std::string>` 来保存每一行的数据条目。以下是具体实现方式:
#### 表格输入的核心逻辑
通过循环不断请求用户输入每列的内容,并将这些内容按照行的形式存入容器之中。当完成所有必要字段的信息采集后,则停止收集流程并将结果打印出来或者继续其他业务逻辑操作。
```cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// Function to display table header dynamically based on column names provided by user or predefined ones.
void showTableHeader(const vector<string>& headers) {
cout << "+-----------------------------+\n"; // Fixed width for simplicity
cout << "| ";
for (const auto& hdr : headers) {
cout << setw(15) << left << hdr.substr(0, 15) << " | "; // Limit each field length to 15 chars
}
cout << "\n+-----------------------------+\n";
}
// Collecting data row-by-row from console until sentinel value entered ('done').
vector<vector<string>> collectDataRows(int numCols) {
vector<vector<string>> rows;
string cellValue;
int rowIndex = 0;
while (true) {
vector<string> currentRow(numCols);
cout << "Enter values for Row #" << ++rowIndex << ": \n";
for (int col = 0; col < numCols; ++col) {
cout << "Column [" << col + 1 << "] Value: ";
getline(cin >> ws, cellValue); // Use getline with manipulator to handle spaces correctly
if ("done" == cellValue && !rows.empty()) {
return rows; // If 'done', exit collection only after at least one valid entry exists.
}
currentRow[col] = move(cellValue);
if (!cellValue.empty() && all_of(cellValue.begin(), cellValue.end(), ::isspace)) {
throw invalid_argument("Empty cells not allowed.");
}
}
rows.emplace_back(move(currentRow));
}
}
// Display collected data in tabular format similar to how it was inputted earlier.
void printDataTable(const vector<string>& headers, const vector<vector<string>>& body) {
showTableHeader(headers);
for (const auto& rowData : body) {
cout << "| ";
for (size_t i = 0; i < rowData.size(); ++i) {
cout << setw(15) << left << rowData[i].substr(0, 15) << " | ";
}
cout << endl;
}
cout << "+-----------------------------+" << endl;
}
int main() try {
const int NUM_COLUMNS = 3; // Example number of columns
cout << "Welcome! Let's create a simple table.\nSpecify three-column entries below:\n";
vector<string> columnNames {"Name", "Age", "Occupation"};
showTableHeader(columnNames);
auto dataTable = collectDataRows(NUM_COLUMNS);
printDataTable(columnNames, dataTable);
} catch (exception& e) {
cerr << "Error occurred during execution: " << e.what() << ". Exiting..." << endl;
return EXIT_FAILURE;
}
```
此代码片段展示了如何构建一个基本但灵活的命令行界面用于录入多行列信息[^3]。它首先定义了一些辅助函数用来展示头部和实际记录部分;接着提供了核心算法让用户能够反复提交新的项目直至他们决定终止会话为止。最后还加入了异常处理器以便更好地应对潜在错误状况的发生。
---
###
仅用<iostream> #include <string> #include <cstdlib> #include <cstring> #include <cctype> #include <cmath> #include <cstdio> #include <cerrno> #include <clocale> #include <ctime> #include <cwchar> #include <cwctype> #include <iomanip> #include <numeric> #include <algorithm> #include <unistd.h> #include <sys/wait.h> #include <conio.h>库实现控制台中点击式交互
### 使用C++标准库实现控制台点击式交互功能
要在基于C++的控制台应用程序中模拟“点击式”交互体验,主要依赖于以下几个方面:实时监听键盘输入、快速响应用户操作以及动态更新屏幕内容。虽然C++标准库本身并不提供直接支持鼠标事件的功能,但可以通过一些技巧来接近这种效果。
#### 实时获取按键状态
在Windows平台上可以使用`_kbhit()`函数判断是否有键被按下,并通过`_getch()`读取具体的按键值[^2]。这两个函数均位于 `<conio.h>` 头文件下,因此需要引入该头文件才能正常使用。
```cpp
#include <conio.h> // For _kbhit and _getch functions
#include <iostream>
bool checkKeyPress(char& pressedKey) {
if (_kbhit()) {
pressedKey = _getch();
return true;
}
return false;
}
int main() {
char key;
while (true) {
if (checkKeyPress(key)) {
std::cout << "Pressed Key: " << key << '\n';
if (key == 'q') break; // Exit loop when 'q' is pressed
}
}
return 0;
}
```
这段代码实现了持续监测键盘输入直到接收到指定退出信号为止的行为模式[^2]。
#### 动态刷新显示界面
为了让用户体验更加友好,在每次接收新输入之后都需要及时调整视图布局。一种简单做法就是先清空现有画布然后再绘制最新的元素集合。下面给出了一种通用解决方案:
```cpp
void clearConsoleScreen() {
#if defined(__linux__) || defined(__APPLE__)
system("clear");
#elif defined(_WIN32) || defined(WIN32)
system("cls");
#else
#error Unsupported platform detected!
#endif
}
void renderMenu(const std::vector<std::string>& options, size_t selectedIndex=0UL) {
clearConsoleScreen();
for(auto idx{0u}; auto&& option : options){
const bool isSelected{(idx==selectedIndex)};
std::cout<<((isSelected)?"> ":" ")<<option<<"\n";
++idx;
}
}
std::pair<size_t,bool> processInput(size_t currentSelection,std::size_t maxIndex){
static constexpr char UP_ARROW{'w'},DOWN_ARROW{'s'};
char inputChar{};
do{
if(!checkKeyPress(inputChar)){
continue;
}
switch(inputChar){
case UP_ARROW:
--currentSelection;
if(currentSelection>(maxIndex-(maxIndex+1))){
currentSelection=maxIndex;
}
break;
case DOWN_ARROW:
++currentSelection;
if(currentSelection>=maxIndex){
currentSelection=0U;
}
break;
default:// Assume any other character as selection confirmation.
return {currentSelection,true};
}
renderMenu({"Option A","Option B"},currentSelection);
}while(true);
return {currentSelection,false};
}
int main(){
size_t selectedIdx{0U},totalOptionsCount{2U};
do{
auto resultPair=processInput(selectedIdx,totalOptionsCount);
selectedIdx=resultPair.first;
}while(false==resultPair.second);
std::cout<<"User has chosen Option "<<selectedIdx+1<<"\n";
return EXIT_SUCCESS;
}
```
上述例子创建了一个简易菜单导航系统,其中包含了上下方向箭头移动高亮项的能力以及最终选定某一项后的反馈消息输出过程[^2]。
---
###
阅读全文
相关推荐
















