UVA10763 Foreign Exchange

链接

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1704

题解

切水题可以愉悦身心,锻练手速
                            ————Claris

把原来序列的两个元素交换下位置得到一个新的序列,如果两个序列完全相同,说明 YES Y E S ,否则 NO N O
判断连个序列是否相同,可以直接计算一个哈希值或者排个序之后逐一比较。
哈希有个点要注意,不要求和,要求积,因为和很容易冲突(WA了3次)

代码1

//排序O(nlogn) 
#include 
#include 
#include 
#include 
#define cl(x) memset(x,0,sizeof(x))
#define maxn 500010
using namespace std;
struct student
{
    int a, b, id;
    bool operator<(student x){return a==x.a?bbool operator!=(student x){return a!=x.a or b!=x.b;}
}list1[maxn], list2[maxn];
int mark[maxn], n;
int  read(int x=0)
{
    char c, f=1;
    for(c=getchar();!isdigit(c) and c^-1;c=getchar())if(c=='-')f=-1;
    for(;isdigit(c);c=getchar())x=(x<<1)+(x<<3)+c-48;
    return f*x; 
}
void init()
{
    int i;
    for(i=1;i<=n;i++)list1[i].a=read(), list1[i].b=read(), list1[i].id=i, list2[i]=list1[i], swap(list2[i].a,list2[i].b);
    sort(list1+1,list1+n+1);
    sort(list2+1,list2+n+1); 
}
bool work()
{
    int res=n<<1, i;
    for(i=1;i<=n;i++)if(list1[i]!=list2[i])return false;
    return true;
}
int main()
{
    for(n=read();n;n=read())
    {
        init();
        if(work())printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

代码2

//哈希O(n)
#include 
#include 
#include 
#include 
#define base 4894651ll
#define mod 1000000007ll
#define maxn 500010
#define ll long long
using namespace std;
struct student
{
    ll a, b;
    ll hash(){return (a*base+b)%mod;}
}list1[maxn], list2[maxn];
ll n;
ll  read(ll x=0)
{
    char c, f=1;
    for(c=getchar();!isdigit(c) and c^-1;c=getchar())if(c=='-')f=-1;
    for(;isdigit(c);c=getchar())x=(x<<1)+(x<<3)+c-48;
    return f*x; 
}
void init()
{
    ll i;
    for(i=1;i<=n;i++)list1[i].a=read(), list1[i].b=read(), list2[i]=list1[i], swap(list2[i].a,list2[i].b);
}
bool work()
{
    ll h1=1, h2=1, i;
    for(i=1;i<=n;i++)h1=(h1*list1[i].hash())%mod;
    for(i=1;i<=n;i++)h2=(h2*list2[i].hash())%mod;
    return h1==h2;
}
int main()
{
    for(n=read();n;n=read())
    {
        init();
        if(work())printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

你可能感兴趣的:(特殊技巧)