#include<bits/stdc++.h>
using namespace std;
#define int long long
#define itn long long
#define x first
#define fst ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define y second
const int N=1e6+5,INF=0x3f3f3f3f3f3f3f3f;
const int mod=1e9+7;
int t;
int x,y;
int ans=0;
int ksm(int a,int b)
{
int uns=1;
while(b)
{
if(b&1)
{
uns*=a;
uns%=mod;
}
b>>=1;
a*=a;
a%=mod;
}
return uns%mod;
}
signed main(){
// freopen("stone.in","r",stdin);
// freopen("stone.out","w",stdout);
cin>>t;
while(t--)
{
cin>>x>>y;
if(x==1)
{
cout<<y<<endl;
continue;
}
if(x==2)
{
cout<<y*(y-1)<<endl;
continue;
}
if(x%2==1)
{
cout<<ksm(y-1,x)-y+1<<endl;
}
else
{
cout<<ksm(y-1,x)+y-1<<endl;
}
}
return 0;
}
t4
```cpp
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define mp make_pair
#define xx first
#define yy second
const int maxn=4010;
vector<int> a[maxn];
int n,m,v[maxn],d[maxn][maxn];
queue<int>p;
pair<int,int> dian[maxn][3];
signed main(){
freopen("tour.in","r",stdin);
freopen("tour.out","w",stdout);
cin>>n>>m;
for(int i=1;i<=m;++i)
{
int x,y;
cin>>x>>y;
a[x].push_back(y);
a[y].push_back(x);
}
for(int i=1;i<=n;++i)
{
int S=i;
d[i][i]=1,p.push(S);
while(p.size())
{
int x=p.front();p.pop();
for(auto y:a[x])
{
if(!d[i][y])d[i][y]=d[i][x]+1,p.push(y);
}
}
for(int j=1;j<=n;++j)
{
if(d[i][j]>=dian[i][0].xx)dian[i][2]=dian[i][1],dian[i][1]=dian[i][0],dian[i][0]=mp(d[i][j],j);
else if(d[i][j]>=dian[i][1].xx)dian[i][2]=dian[i][1],dian[i][1]=mp(d[i][j],j);
else dian[i][2]=max(dian[i][2],mp(d[i][j],j));
}
}
int ans=0;
for(int i=1;i<=n;++i)
for(int j=i+1;j<=n;++j)
{
int st=0;
v[i]=1,v[j]=1;
for(int k=0;k<3;++k)
if(!v[dian[i][k].yy])
{
st=k;
break;
}
v[dian[i][st].yy]=1;
for(int k=0;k<3;++k)
if(!v[dian[j][k].yy])
{
ans=max(ans,d[i][j]+dian[i][st].xx+dian[j][k].xx);
break;
}
v[dian[i][st].yy]=0;
for(int k=0;k<3;++k)
{
if(!v[dian[j][k].yy]){st=k;break;}
}
v[dian[j][st].yy]=1;
for(int k=0;k<3;++k)
if(!v[dian[i][k].yy])
{
ans=max(ans,d[i][j]+dian[j][st].xx+dian[i][k].xx);
break;
}
v[dian[j][st].yy]=0;
v[i]=v[j]=0;
}
cout<<ans-3<<endl;
return 0;
}
```