题目:
代码:
#include<bits/stdc++.h>
typedef struct ListNode_City {
int val;
int sign;
struct ListNode_City* next = NULL;
}ListNode_City;
ListNode_City* BuyNode(int val) {
ListNode_City* newNode = (ListNode_City*)malloc(sizeof(ListNode_City));
if (newNode == NULL) {
printf("mallc fail\n");
}
newNode->next = NULL;
newNode->val = val;
newNode->sign = 0;
return newNode;
}
ListNode_City* CreatList(int n,int k) {
ListNode_City* head = BuyNode(0);
ListNode_City* tail = head;
ListNode_City* prev = head;
if (1 == k) {
tail->sign = 1;
}
for (int i = 1; i <= n; i++) {
tail->next = BuyNode(i);
tail = tail->next;
if (i == k) {
tail->sign = 1;
}
}
tail->next = head;
return head;
}
int solve(int n, int j,int k) {
ListNode_City* head = CreatList(n,k);
ListNode_City* cur = head;
int count = n;
while (cur->next != cur) {
int tmp = j;
if (cur->val == 0) {
ListNode_City* prev = cur;
while (prev->next != cur) {
prev = prev->next;
}
ListNode_City* tmpp = cur;
cur = prev;
cur->next = tmpp->next;
prev = tmpp;
free(prev);
count--;
}
else {
while (--tmp) {
cur = cur->next;
}
ListNode_City* delNode = cur->next;
if (delNode->sign == 1 && count != 0) {
return 0;
}
if (cur->sign == 0)
cur->sign = 0;
else
cur->sign = 1;
cur->next = delNode->next;
free(delNode);
delNode = NULL;
count--;
if (count == 0) {
return true;
}
}
if (cur->next == cur) {
return true;
}
}
}
int main() {
int N = 0;
scanf("%d", &N);
while (N--) {
int n, k;
int ans = 0;
scanf("%d%d", &n, &k);
int flag = 0;
if (n == k) {
printf("1\n");
flag = 1;
}
if (n < k) {
printf("No Solution!\n");
flag = 1;
}
if (flag == 0) {
for (int j = 3; j <= n; j++) {
ans = solve(n, j, k);
if (ans == 1) {
printf("%d\n", j);
break;
}
}
if (ans == 0)
printf("No Solution!\n");
}
}
return 0;
}