http://acm.hdu.edu.cn/showproblem.php?pid=1222
我本来想做到约瑟夫环的题目,百度了一下,说hdu1222是关于约瑟夫环的,这于是我写了个约瑟夫环的循环单链表的代码,结果坑爹了,超时。最后想想,这道题根本不要用循环单链表来求解。只要验证m 与n是否互质就行了。下面是代码,第一个是我利用循环单链表的代码,应该正确,但是超时:
#include <stdio.h>
#include <malloc.h>
typedef struct node
{
bool ss;
node *next;
}node;
int main()
{
int n, m, p;
while (scanf("%d", &p) != EOF)
{
while(p --)
{
scanf("%d%d", &m, &n);
node *head, *p;
head = (node*)malloc(sizeof(node));
head -> ss = 0;
p = head;
int j, w;
j = n;
w = m;
while (j--)
{
node *temp;
temp = (node*)malloc(sizeof(node));
temp -> ss = 0;
p -> next = temp;
p = temp;
}
p -> next = head -> next;
head = head -> next;
node *g;
g = head;
bool b = 0;
j = n;
while (j--)
{
if (g -> ss == 1)
{
printf("YES\n");
b = g -> ss;
break;
}
g -> ss = 1;
w = m;
while (w)
{
g = g -> next;
w--;
}
}
if (b == 0)
printf("NO\n");
}
}
system ("pause");
return 0;
}
接下来是我的利用辗转相除法求最大公约数,判断是否互质,最后判断YES or NO的问题
#include <iostream>
using namespace std;
int gcd(int a,int b)
{
return !b?a:gcd(b,a%b);
}
int main()
{
int sum;
cin>>sum;
while(sum--)
{
int a,b;
cin>>a>>b;
if(gcd(a,b)==1) cout<<"NO"<<endl;
else cout<<"YES"<<endl;
}
system ("pause");
return 0;
}