Codeforces 1036B Diagonal Walking v.2 【贪心】

题目传送门:https://codeforces.com/contest/1036/problem/B

被这道题坑了,说白了还是菜。

贪心策略是先斜对角从(0,0)走到(n,n),然后往右拐(分奇偶考虑)【若n>m,swap(n,m)】

理论上是画画图,知道切入点是奇偶性后,就能想清楚了

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<vector>
#define INF 2e9
using namespace std;



int main(){
    ios::sync_with_stdio(false);
    int q; cin>>q;
    while(q--){
        long long n,m,k; cin>>n>>m>>k;
        //from (0,0) to (n,m)
        if(n>m) swap(m,n);
        // get n<=m
        
        //from (0,0) to (n,n)
        long long cnt=n;
        if( (m-n)%2==1 ){//from (n,n) to (n,m-1)
            cnt+=m-n-1;
            k-=cnt;
            if(k<=0){ cout<<-1<<endl; }
            else{
                k-=1;
                cnt+=k;
                cout<<cnt<<endl;
            }
        }
        else{//from (n,n) to (n,m)
            cnt+=m-n;
            k-=cnt;
            if( k<0 ) cout<<-1<<endl;
            else if( k==0 ) cout<<cnt<<endl;
            else{
                long long zero=0;
                if(k%2==0) cout<<cnt+k<<endl;
                else{
                    if(k==1) cout<<cnt-1<<endl;
                    else cout<<cnt+k-2<<endl;
                }
            }
        }
    }
    
    return 0;    
}
原文地址:https://www.cnblogs.com/ZhenghangHu/p/9678767.html