本文主要是介绍hdu1573 X问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原题:
http://acm.hdu.edu.cn/showproblem.php?pid=1573
这个题目真是坑爹啊- =首先说M个正整数,结果测试数据里面就有0 - =莫非0成了正整数?
扩展中国剩余定理解这道题目很多模板也不对- =造呢。。也不知道到底可不可以从0开始- =坑爹的题目。。
如果时间急别在这里干着急了- =坑死人
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define lln long long intlln a[11];
lln b[11];lln gcd( lln a, lln b)
{return b == 0 ? a : gcd(b, a % b);
}void ace()
{int n, m;int t;int i, j;int lcm;bool flag;int num;cin >> t;while (t--){memset(a, 0, sizeof(a));memset(b, 0, sizeof(b));cin >> n >> m;lcm = 1;flag = false;num = 0;for (i = 0; i < m; i++){cin >> a[i];lcm = lcm * a[i] / gcd(lcm, a[i]);}for (i = 0; i < m; i++)cin >> b[i];for (i = 1; i <= lcm && i <= n; i++) //find the minium num 坑爹的地方- - i不能从0开始{for (j = 0; j < m; j++)if (i % a[j] != b[j])break;if (j == m){flag = true;break;}}if (flag){int temp = n % lcm;if (temp >= i)i = n / lcm + 1;elsei = n / lcm;printf("%d\n", i);
// while (i <= n)
// {
// i += lcm;
// num++;
// }
// cout << num << endl;}elseprintf("0\n");}
}
int main()
{ace();return 0;
}
/**
中国剩余定理(不互质)模板
*/
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef __int64 int64;
int64 Mod;int64 gcd(int64 a, int64 b)
{if(b==0)return a;return gcd(b,a%b);
}int64 Extend_Euclid(int64 a, int64 b, int64&x, int64& y)
{if(b==0){x=1,y=0;return a;}int64 d = Extend_Euclid(b,a%b,x,y);int64 t = x;x = y;y = t - a/b*y;return d;
}//a在模n乘法下的逆元,没有则返回-1
int64 inv(int64 a, int64 n)
{int64 x,y;int64 t = Extend_Euclid(a,n,x,y);if(t != 1)return -1;return (x%n+n)%n;
}//将两个方程合并为一个
bool merge(int64 a1, int64 n1, int64 a2, int64 n2, int64& a3, int64& n3)
{int64 d = gcd(n1,n2);int64 c = a2-a1;if(c%d)return false;c = (c%n2+n2)%n2;c /= d;n1 /= d;n2 /= d;c *= inv(n1,n2);c %= n2;c *= n1*d;c += a1;n3 = n1*n2*d;a3 = (c%n3+n3)%n3;return true;
}//求模线性方程组x=ai(mod ni),ni可以不互质
int64 China_Reminder2(int len, int64* a, int64* n)
{int64 a1=a[0],n1=n[0];int64 a2,n2;for(int i = 1; i < len; i++){int64 aa,nn;a2 = a[i],n2=n[i];if(!merge(a1,n1,a2,n2,aa,nn))return -1;a1 = aa;n1 = nn;}Mod = n1;return (a1%n1+n1)%n1;
}
int64 a[1000],b[1000];
int main()
{int i;int k;while(scanf("%d",&k)!=EOF){for(i = 0; i < k; i++)scanf("%I64d %I64d",&a[i],&b[i]);printf("%I64d\n",China_Reminder2(k,b,a));}return 0;
}
这篇关于hdu1573 X问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!